mitt版本2.1.0使用问题
来源:5-11 使用新版 mitt 时报出类型错误的解决方案
不染的卡卡
2023-12-04
<script lang="ts"> import { defineComponent, onUnmounted } from 'vue' import mitt from 'mitt' type ValidateFunc = () => boolean export const emitter = mitt() export default defineComponent({ emits: ['form-submit'], setup(props, context) { let funcArr: ValidateFunc[] = [] const submitForm = () => { const result = funcArr.map(func => func()).every(result => result) context.emit('form-submit', result) } const callback = (func?: ValidateFunc) => { if (func) { funcArr.push(func) } } emitter.on('form-item-created', callback) onUnmounted(() => { emitter.off('form-item-created', callback) funcArr = [] }) return { submitForm } } }) </script> 问题:报错 没有与此调用匹配的重载。 第 1 个重载(共 2 个),“(type: "*", handler: WildcardHandler<Record<EventType, unknown>>): void”,出现以下错误。 第 2 个重载(共 2 个),“(type: "form-item-created", handler: Handler<unknown>): void”,出现以下错误。ts(2769) (method) Emitter<Record<EventType, unknown>>.on(type: "*", handler: WildcardHandler<Record<EventType, unknown>>): void (+1 overload)
写回答
1回答
-
不染的卡卡
提问者
2023-12-04
已经解决
版本是3.0.1,解决方法如下
<script lang="ts"> import { defineComponent, onUnmounted } from 'vue' // 现在mitt要求每个事件名称和事件类型要一一对应 import mitt from 'mitt' type ValidateFunc = () => boolean type Events = { 'form-item-created': ValidateFunc }// 定义一个Event类型 这个对应是让事件和对应的callback 一一对应 export const emitter = mitt<Events>()// 实例化 mitt 的时候,作为泛型传递进去 export default defineComponent({ emits: ['form-submit'], setup(props, context) { let funcArr: ValidateFunc[] = [] const submitForm = () => { const result = funcArr.map(func => func()).every(result => result) context.emit('form-submit', result) } const callback = (func?: ValidateFunc) => { if (func) { funcArr.push(func) } } emitter.on('form-item-created', callback) onUnmounted(() => { emitter.off('form-item-created', callback) funcArr = [] }) return { submitForm } } }) </script> <style scoped></style>
10
相似问题