vue3子父组件通信

109 阅读1分钟

自定义事件配合 defineEmits() 传参

image.png

父组件代码
<template>
    <div class="wrap">
        <h1>vue常见传参方式</h1>
        <p>props传值</p>
        <p>{{ title }}</p>
        <!-- 通过v-bind动态传参 可以简写为:-->
        <childCmp @getchildval="getchildvalFun" :dataTitle="title"></childCmp>
    </div>
</template>
<script setup lang="ts">
// 引入api
import { ref } from "vue"
// 引入组件
import childCmp from "@/components/cmp/prop.vue"
let title=ref("测试数据")//创建动态数据
let getchildvalFun=(val)=>{// 自定义事件回掉函数
	title.value=val//修改父组件数据
}
</script>
子组件代码
<template>
    <div class="child">
        <h1>我是子组件</h1>
        <p>父组件传递过来的数据:{{ dataTitle }}</p>
        <button @click="emitParent">点击按钮向父组件传递数据</button>
    </div>
</template>
<script setup>
//定义变量接受 在js区域访问 需要添加props前缀
const props = defineProps({
	dataTitle:String// 添加校验类型
});
const emit=defineEmits(["getchildval"])//接收自定义事件
const emitParent=()=>{// 点击事件执行函数
	emit("getchildval","我是子组件的数据")// 触发父组件自定义事件 传参
}
</script>
<style scoped lang="scss">
	.child{
		width: 200px;
		height: 200px;
		background: skyblue;
	}
</style>
总结

父组件调用子组件通过自定义事件获取子组件传递出的数据,子组件内部通过defineEmits()接收及触发自定义事件完成传参