Skip to content

Commit

Permalink
emit support multiple -
Browse files Browse the repository at this point in the history
  • Loading branch information
cuixiaorui committed Feb 3, 2021
1 parent 7135d68 commit 6e4911e
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 3 deletions.
4 changes: 4 additions & 0 deletions example/components/componentEmit.js/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ export default {
console.log("---------------change------------------");
console.log(a, b);
},
onChangePageName(a, b) {
console.log("---------------change-page-name------------------");
console.log(a, b);
},
}),
]);
},
Expand Down
4 changes: 3 additions & 1 deletion example/components/componentEmit.js/Child.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { h, ref, reactive } from "../../../lib/mini-vue.esm.js";
export default {
name: "Child",
setup(props, { emit }) {
emit("change", "aaaaa","bbbbbb");
emit("change", "aaaaa", "bbbbbb");
// 支持多个 -
emit("change-page-name", "start", "game");
},
render() {
return h("div", {}, "child");
Expand Down
2 changes: 1 addition & 1 deletion src/runtime-core/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function createComponentInstance(vnode) {
isMounted: false,
attrs: {}, // 存放 attrs 的数据
slots: {}, // 存放插槽的数据
emit: () => {}, // TODO 需要实现 emit 函数
emit: () => {},
};

// 赋值 emit
Expand Down
4 changes: 3 additions & 1 deletion src/runtime-core/componentEmits.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { camelize, toHandlerKey } from "../shared/index";
export function emit(instance, event: string, ...rawArgs) {
// 1. emit 是基于 props 里面的 onXXX 的函数来进行匹配的
// 所以我们先从 props 中看看是否有对应的 event handler
const props = instance.props;
// ex: event -> click 那么这里取的就是 onClick
// 让事情变的复杂一点如果是烤肉串命名的话,需要转换成 change-page -> changePage
// 需要得到事件名称
const handlerName = "on" + event.charAt(0).toUpperCase() + event.slice(1);
const handlerName = toHandlerKey(camelize(event));
const handler = props[handlerName];
if (handler) {
handler(...rawArgs);
Expand Down
23 changes: 23 additions & 0 deletions src/shared/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,24 @@
export * from "./shapeFlags";

const camelizeRE = /-(\w)/g;
/**
* @private
* 把烤肉串命名方式转换成驼峰命名方式
*/
export const camelize = (str: string): string => {
return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ""));
};

/**
* @private
* 首字母大写
*/
export const capitalize = (str: string) =>
str.charAt(0).toUpperCase() + str.slice(1);

/**
* @private
* 添加 on 前缀,并且首字母大写
*/
export const toHandlerKey = (str: string) =>
str ? `on${capitalize(str)}` : ``;

0 comments on commit 6e4911e

Please sign in to comment.