问题
我们都知道,setUp 方法里面有两个参数,一个是 props
,一个是 context
。
export default {
setup(props, context) {
context.emit("event");
},
};
可以在 context
对象里面获取到 emit
方法直接调用。但是在自定义方法里面,怎么使用 emit() 方法呢?
解决
vue 库里面提供了 defineEmits
方法,可以获取到 emit() 方法。
<script setup lang="ts">
import { defineEmits } from 'vue'
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string): void
}>()
function yourFunction (id: number) {
emit('change', id)
}
<script>
纯 JS 版本,可以使用下面的代码
<script setup>
const emit = defineEmits()
emit('type', 'data')
<script>