vue3中组件传递消息

本文介绍了Vue3中四种主要的组件间通信方式:通过props从父向子传递值,使用ref调用子组件方法,利用provide/inject进行爷孙组件通信,以及借助mitt实现兄弟组件间的通信。详细讲解了每种方式的使用方法和场景。
摘要由CSDN通过智能技术生成

嗨!我是浮生code,一个努力向上爬的蜗牛程序员。通过自己的经验,这期分享一下vue3中的传递方式,解决有些从vue2转vue3的人,会遇到的组件传递消息的一些问题,

第一种父向子-传值(props)

//子组件中
<script setup>
const props = defineProps({
    name:{
        type: String,
        default: ''
    },
})
</script>

<template>

<child  :name="name"/>
</template>

//父组件中传值
<script setup>
import child from '@/component/child.vue'
let name = ref('嗨,我是浮生code')
</script>

第二种父调用子 方法 (ref)

//子组件
<template>
    <div @click='toDo'>点击</div>
</template>

<script setup>
const emit = defineEmits(["doSome"])

function toDo() {
    emit('doSome','嗨,我是浮生code')
}
</script>


//父组件
<template>
    <child @doSome="doSome"/>
</template>

<script setup>
import child from '@/component/child.vue'

function doSome(e) {
    console.log(e) //拿到数据   嗨,我是浮生code
}

</script>

第三种 爷孙传递消息(只能由顶层传递到下层)(provide、inject)

注意:如果需要改变数据建议使用 ref(),因为小编在使用时reactive(),修改的数据时,子组件没有变化

//父组件
<template>
    <div @click="change"></div>
    <son/>
</template>
<script setup>
    import son from '@/components/son';
    let content = ref('你好')
    provide('content',content)

    function change(){
        content.value = '你好,我是浮生code'
    }
</script>


//子组件
<template>
    <grandson/>
</template>
<script setup>
    import grandson from '@/components/grandson';
</script>


//孙子组件
<template>
    <div>{{ content }}</div>
</template>
<script setup>
    let content= inject('content')
</script>

第四种 兄弟组件(mitt)

第四种方式类似于vue2中的bus,但vue3中已经没有了,也可以自己写,也可以调用vue3中的第三方的东西,小编推荐调用第三方来传递消息。

第一步:安装mitt

npm install --save mitt 

第二步:创建js文件,引入mitt(例如:bus.js)

import mitt from 'mitt'
const bus = mitt()
export default bus

第三步调用
 

//兄弟组件1
<template>
    <div @click='toInfos'></div>
</template>
<script setup>
import bus from "../bus.js";

function toInfos() {
  bus.emit('infos','给兄弟2的消息')
}
</script>

//兄弟组件2
<template>
    <div></div>
</template>
<script setup>
import bus from "../bus.js";
bus.on("infos",(e)=>{
    console.log(e) //拿到数据  给兄弟2的消息
})
</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值