【问题标题】:Vue 3 - Composition Api - Typescript -> type of emitVue 3 - Composition Api - Typescript -> 发射类型
【发布时间】:2021-05-31 03:10:12
【问题描述】:
我从 VUE 3 和第一次使用 Typescript 的组合 API 开始。
我有如下设置方法:
setup(props: { widgetType: string; displayType: string; trigger: number }, { emit })
现在,当我构建这个文件时,我收到错误“绑定元素'emit'隐式具有'any'类型。”。
我不知道如何解决这个问题。我尝试了来自网络的不同解决方案,但没有任何效果。
有谁能够帮我?
问候
克里斯
【问题讨论】:
标签:
typescript
vue.js
composition
【解决方案1】:
例如正确键入组件“App”和可组合“useModal”
应用:
<script lang="ts">
import {defineComponent, SetupContext, ComponentPropsOptions} from 'vue';
import {useModal} from '@/composable/useModal';
export default defineComponent({
name: 'App',
setup(props: ComponentPropsOptions, {emit}: SetupContext) {
const openModal = useModal({emit});
return {openModal};
}
});
</script>
使用模式:
import {SetupContext} from 'vue';
interface UseModalProps {
emit: SetupContext['emit'];
}
export function useModal({emit}: UseModalProps) {
function openModal({title, type}: {title: string; type: string}): void {
emit('openModal', {title, type});
}
return {openModal};
}
【解决方案2】:
您需要使用defineComponent 方法定义您的组件并将正确的类型应用于道具。如果您使用的是单个文件组件,它看起来像这样
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
props: {
widgetType: {
type: String,
required: true
},
displayType: {
type: String,
required: true
},
trigger: {
type: number,
required: true
}
},
setup(props, { emit }) {
// Rest of your setup code here
}
});
</script>
【解决方案3】:
要做一个快速的脏修复,你可以这样做:
setup(props: { widgetType: string; displayType: string; trigger: number }, { emit }: { emit: Function | (eventName: string, payload: any) => void })
但我建议您使用整个组件更新您的问题,以便我们了解问题的根本原因