Vue 3 - 组合 API - 打字稿 - > 发送类型



我第一次使用Typescript从VUE 3和composition api开始。我有如下设置方法:setup(props: { widgetType: string; displayType: string; trigger: number }, { emit })现在,当我构建这个文件时,我得到了错误"绑定元素'emit'隐式地具有'any'类型"。我不知道如何解决这个问题。我从网上尝试了不同的解决方案,但都不起作用。有人能帮帮我吗?问候克里斯。

您需要使用defineComponent方法定义您的组件,并为props应用正确的类型。如果你使用的是单文件组件,它看起来会像这样

<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>

例如正确输入组件"App"和可组合"useModal">

应用程序:

<script lang="ts"> 
import {defineComponent, SetupContext, ComponentPropsOptions} from 'vue';
import {useModal} from '@/composable/useModal';

export default defineComponent({
name: 'App',
emits: ['openModal'],
setup(props: ComponentPropsOptions, {emit}: SetupContext) {
const openModal = useModal({emit});

return {openModal};
}
});
</script>

useModal:

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};
}

相关内容

最新更新