Cha*_*lie 4 typescript vue.js vuejs3
我正在寻找是否可以定义发出的类型。在脚本设置中的 SFC 中,我们可以执行以下操作(文档):
<script setup lang="ts">
// runtime
const emit = defineEmits(['change', 'update'])
// type-based
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string): void
}>()
</script>
Run Code Online (Sandbox Code Playgroud)
因为我正在寻找一种定义相同事物但基于渲染函数的方法:
export const ComponentA = defineComponent({
props: {...},
setup() {
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string): void
}>()
}
})
Run Code Online (Sandbox Code Playgroud)
不幸的是我收到以下错误defineEmits() is a compiler-hint helper that is only usable inside <script setup> of a single file component.
。
有没有办法定义正在触发的事件及其类型?
ton*_*y19 11
您不能在 内部声明发射setup()
,但可以在钩子旁边使用该emits
选项setup()
,并从上下文参数的emit
属性访问发射(即,通过 的第二个参数setup()
):
import { defineComponent } from 'vue'
export const ComponentA = defineComponent({
emits: {
change: (id: number) => true,
update: (value: string) => true,
},
setup(props, { emit }) {
// @ts-expect-error
emit('change', 'foo')
// @ts-expect-error
emit('update', 100)
// ok
emit('change', 100)
// ok
emit('update', 'x')
}
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10341 次 |
最近记录: |