Vue3父子通信

1.子组件调用父组件,子组件向父组件传值

//父组件代码

<script setup>
// 引入子组件
import son from './components/son.vue'
//子组件要调用的父组件的方法
const getMessage = (msg)=>{
  console.log(msg);
}
</script>

<template>
//绑定制自定义事件
  <son @get-message="getMessage"></son>
</template>





//子组件代码

<script setup>
//2.使用defineEmits编译器宏函数生成emit方法
const emit = defineEmits(['get-message'])
const sendMsg =()=>{
//3.触发自定义函数
    emit('get-message','this is son')
}
</script>
<template>
    <div @click="sendMsg">
        按钮
    </div>
</template>

2.父组件向子组件传值

//父组件
<script>
//引入子组件
import son from './components/son.vue'
const mess = ref(20)
const messAdd = () => {
  mess.value++
}
</script>

<template>
//1.绑定属性mess
  <son :mess="mess" @click="messAdd"></son>
</template>







//子组件
<script setup>
//2.defineProps接受数据
const props = defineProps({
    mess: Number,
})
</script>
<template>
    <div>
        父组件传入的数据:{{ props.mess }}
    </div>
</template>

3.使用provide传值,用inject接收

//顶级组件
<script setup>
import { provide, reactive, ref, watch } from "vue"

//引入子组件
import son from './components/son.vue'
const mess = ref(20)
const messAdd = () => {
  mess.value++
}

// 1.顶层组件提供数据
//使用provide传递参数
provide('fatherData', "我是爷爷传过来的数据")

// 顶层组件提供动态数据
provide('dongtai', mess)

//顶层把自己的方法传递出去
provide('addfather', messAdd)

</script>

<template>
  <div>父亲:{{ mess }}</div>
  <son></son>
</template>

<style scoped></style>





//儿子组件
<script setup>
import{inject, ref} from 'vue'

//引入子组件
import grandson from './grandson.vue'

//使用inject接收顶层传递的参数
const dongtai = inject('dongtai')
const num = ref(dongtai)
</script>

<template>
    <div>儿子:{{ num }}</div>
    <grandson></grandson>
</template>
<style></style>






//孙子组件
<script setup>
import { inject } from 'vue';

//使用inject接收顶层传递的参数
const geandSon = inject('fatherData')
const dongtai = inject('dongtai')

//调用顶层方法
const addfather = inject('addfather')
</script>

<template>
<div>孙子:{{ geandSon }}</div>
<div>孙子:{{ dongtai }}</div>
<bottom @click="addfather">孙子:点击把爷爷+1</bottom>
</template>

<style>
div {
  font-size: 30px;
}
</style>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值