Emit 的实现
开发者接口
继props之后,我们来实现emit。 emit的实现相对简单,很快就能完成。
在开发者接口方面,我们将emit设计为可以从setup函数的第2个参数中获取。
ts
const MyComponent: Component = {
props: { someMessage: { type: String } },
setup(props: any, { emit }: any) {
return () =>
h('div', {}, [
h('p', {}, [`someMessage: ${props.someMessage}`]),
h('button', { onClick: () => emit('click:change-message') }, [
'change message',
]),
])
},
}
const app = createApp({
setup() {
const state = reactive({ message: 'hello' })
const changeMessage = () => {
state.message += '!'
}
return () =>
h('div', { id: 'my-app' }, [
h(
MyComponent,
{
'some-message': state.message,
'onClick:change-message': changeMessage,
},
[],
),
])
},
})
实现
和props一样,我们创建一个~/packages/runtime-core/componentEmits.ts
文件并在其中实现。 emit的实现很简单,就是在instance中实现emit函数,执行时从vnode的props中查找对应的处理函数并执行。
~/packages/runtime-core/componentEmits.ts
ts
export function emit(
instance: ComponentInternalInstance,
event: string,
...rawArgs: any[]
) {
const props = instance.vnode.props || {}
let args = rawArgs
let handler =
props[toHandlerKey(event)] || props[toHandlerKey(camelize(event))]
if (handler) handler(...args)
}
~/packages/shared/general.ts
ts
export const capitalize = (str: string) =>
str.charAt(0).toUpperCase() + str.slice(1)
export const toHandlerKey = (str: string) => (str ? `on${capitalize(str)}` : ``)
~/packages/runtime-core/component.ts
ts
export interface ComponentInternalInstance {
// .
// .
// .
emit: (event: string, ...args: any[]) => void
}
export function createComponentInstance(
vnode: VNode,
): ComponentInternalInstance {
const type = vnode.type as Component
const instance: ComponentInternalInstance = {
// .
// .
// .
emit: null!, // 将立即设置
}
instance.emit = emit.bind(null, instance)
return instance
}
然后我们只需要将它传递给setup函数即可。
~/packages/runtime-core/componentOptions.ts
ts
export type ComponentOptions = {
props?: Record<string, any>
setup?: (
props: Record<string, any>,
ctx: { emit: (event: string, ...args: any[]) => void },
) => Function // 修改为可接收ctx.emit
render?: Function
}
ts
const mountComponent = (initialVNode: VNode, container: RendererElement) => {
const instance: ComponentInternalInstance = (initialVNode.component =
createComponentInstance(initialVNode));
const { props } = instance.vnode;
initProps(instance, props);
const component = initialVNode.type as Component;
if (component.setup) {
// 传递emit
instance.render = component.setup(instance.props, {
emit: instance.emit,
}) as InternalRenderFunction;
}
让我们用前面设想的开发者接口示例来验证一下功能吧! 如果一切正常,我们现在就可以通过props/emit实现组件间的交互了!
到目前为止的源代码:
chibivue (GitHub)