我正在使用 Vue 3 和 TS 4.4。我有一个组件,它用defineProps
. 当我添加对 的调用时defineEmits
,VS Code 开始告诉我props
组件模板中不存在我的变量。这是源代码:
<script setup lang="ts">
import { defineProps, defineEmits, VueElement, defineComponent } from "vue";
const emit = defineEmits<{
"update:checked": boolean;
}>();
const props = defineProps<{
label?: VueElement | string;
checked?: boolean;
}>();
</script>
<template>
<label>
<input
type="checkbox"
:checked="props.checked"
@change="(event) => emit('update:checked', (event.target as any)?.checked)"
/>
{{ props.label }}
</label>
</template>
还有一些屏幕截图可以更好地展示我在 VS Code 中看到的内容。这是添加后defineEmits
:
这是没有defineEmits
:
为道具和发射定义类型的正确方法是什么?
在defineEmits<T>()
一般的参数本质上是一个打字稿接口仅定义功能,其中接收特定事件名称和可选参数:
interface Emits {
(e: __EVENT1_NAME__ [, arg1: __ARG1_TYPE__ [, arg2: __ARG2_TYPE__]]...): void
(e: __EVENT2_NAME__ [, arg1: __ARG1_TYPE__ [, arg2: __ARG2_TYPE__]]...): void
}
例子:
// as inline type
const emits = defineEmits<{
(eventName: 'hover', hovering: boolean): void
(eventName: 'changed', newValue: number, id: string): void
}>()
// as interface
interface Emits {
(eventName: 'hover', hovering: boolean): void
(eventName: 'changed', newValue: number, id: string): void
}
const emits = defineEmits<Emits>()
// as type alias
type Emits = {
(eventName: 'hover', hovering: boolean): void
(eventName: 'changed', newValue: number, id: string): void
}
const emits = defineEmits<Emits>()
对于您的update:checked
事件,代码应类似于以下内容:
// as inline type
const emits = defineEmits<{
(e: 'update:checked', checked: boolean): void
}>()
// as interface
interface Emits {
(e: 'update:checked', checked: boolean): void
}
const emits = defineEmits<Emits>()
// as type alias
type Emits = {
(e: 'update:checked', checked: boolean): void
}
const emits = defineEmits<Emits>()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句