和 Vue2 子传父案例简单入门 相比,Vue 3 子传父的 emit 使用略有不同,同样 通过 Father.vue 和 Child.vue 展示
首先是 Child.vue,重点在 setup 函数中引入 context 形参,配合 emit 使用。定义了两个函数,toFatherNum(), toFatherObject() 分别向父组件传递数字和对象
<template><a-button @click="toFatherNum">子传父数字</a-button><a-button @click="toFatherObject">子传父对象</a-button>
</template><script lang="ts">
import {
defineComponent } from 'vue'
export default defineComponent({
name: "Child",setup(props, context) {
function toFatherNum() {
context.emit('eventIsNum', 888)}function toFatherObject() {
context.emit('eventIsObject', {
keyName: 'I am value' })}return{
toFatherNum,toFatherObject,}}
})
</script><style scoped></style>
然后是 Father.vue,通过事件名称 eventIsNum 和 eventIsObject 接收子组件传递的值,通过打印简单展示传值成功
<template><Child@eventIsNum="receiveChildNum"@eventIsObject="receiveChildObject"></Child>
</template><script lang="ts">
import {
defineComponent } from 'vue'
import Child from "./Child.vue";
export default defineComponent({
name: "Father",components: {
Child,},setup() {
function receiveChildNum(e: number) {
console.log(e, '接收子组件数字');}function receiveChildObject(e: object) {
console.log(e, '接收子组件对象');}return {
receiveChildNum,receiveChildObject,}}
})
</script><style scoped></style>