Vue3实现父子通信(组合式API)

父传子

基本思想:1.父组件中给子组件绑定属性;2.子组件内部通过props选项接收数据
代码展示:

在APP组件中,引入父组件并在<template>标签中使用

父组件:
<template>
  <h3>我是父组件</h3>
   <!-- 1.绑定响应式属性:msg -->
  <child :msg="message" />
</template>
<script setup>
import { ref } from "vue";
//导入子组件
import child from "./child.vue";
const message = ref("父组件传递的信息");
</script>
子组件:
<template>
  <h3>我是子组件</h3>
  <h3>{{ msg }}</h3>
</template>
<script setup>
// 通过编译器宏defineProps接收父组件传递的数据
defineProps({
  msg: String,
});
</script>

浏览器展示:

 子传父

基本思想:1.父组件中给子组件标签通过@绑定事件  2.子组件内部通过自定义方法触发事件
代码展示:

在APP组件中,引入父组件并在<template>标签中使用

 父组件:
<template>
  <h3>{{ title }}</h3>
  <!-- 1.绑定自定义事件 -->
  <child1 @toSonChild="childMessage" />
</template>
<script setup>
import { ref } from "vue";
// 引入子组件
import child1 from "./child1.vue";
const title = ref("我是父组件");
const childMessage = (data) => {
  title.value = data;
};
</script>
子组件:
<template>
  <h3>我是子组件</h3>
  <button @click="passMessage">向父组件传递参数</button>
</template>
<script setup>
// 通过编译器宏defineEmits生成changeFather(可以自己更换)方法
const changeFather = defineEmits(["toSonChild"]);
// 触发自定义事件,并传递参数
const passMessage = () => {
  changeFather("toSonChild", "我是子组件传递的数据");
};
</script>

浏览器展示:

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值