vue3 Emit
2024年1月25日小于 1 分钟约 281 字
在使用vue3 setup方式,组件开如时,emit事件需要提前声明。先通过defineEmits对当前组件所有需要用到的emit事件进行声明,实现如下代码。
<script setup>
const emit = defineEmits(["itemClick"]);
//...
const itemClick = () => {
emit("itemClick", { ...itemdata });
};
</script>以下代码是如何发送消息:
setup(props, context) {
setTimeout(() => {
context.emit("showSYCM", "allen");
}, 1200);
return {};
}以下代码是如何接收消息:
export default {
components: {},
emits: {
showSYCM: val => {
console.log(val);
return true;
}
},
setup(props, context) {
return { showFlag };
}
};
</script>注意,接收消息的函数必须返回true,要不然vue会有警告:
Invalid event arguments: event validation failed for event "showSYCM".
注意:emit函数的第二个参数,可以是一个ref变量,你也可以在接收消息的函数里修改这个ref变量的值。
setup function takes two arguments, First one is props. And the second one is context which exposes three component properties, attrs, slots and emit.
You can access emit from context like:
export default {
setup(props, context) {
context.emit('event');
},
};or
export default {
setup(props, { emit }) {
emit('event');
},
};