外观风格
Vue3 事件声明
为了让事件获得完整的类型推断,我们需要使用 defineEmits
API。
- 类型声明
<script setup lang="ts">
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string, ...rest: any[]): void
}>()
</script>
1
2
3
4
5
6
2
3
4
5
6
当你使用 vue@3.3+
版本时,可以使用以下更为简洁的声明方式:
<script setup lang="ts">
const emit = defineEmits<{
change: [id: number]
update: [name: string, ...rest: any[]]
}>()
</script>
1
2
3
4
5
6
2
3
4
5
6
在上面的代码中,我们声明了 change
和 update
,两个事件,id
和 value
分别为两个事件的参数。
- 运行时声明
<script setup lang="ts">
const emit = defineEmits(['change', 'update'])
</script>
1
2
3
2
3
如果不使用 script setup
的写法,则是:
<script>
import { defineComponent } from 'vue'
export default defineComponent({
emits: ['change'],
setup(props, { emit }) {
emit('change') // <-- 类型检查 / 自动补全
}
})
</script>
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
推荐使用类型声明的方式来声明事件,能直接让我们控制事件的参数和返回值的类型。