首页 > 技术文章 > vue 组件通信集合

cntian 2020-08-05 11:55 原文

父子组件通信:

1. props / $emit,

通过父组件 :msg="msg" 绑定数据
子组件 props 接收数据


子组件 绑定 @click="msg"
methods:{
    msg(){
        this.$emit('showMsg',data)
    } 
}
父组件 绑定 @showMsg=""
data(){
    return{
        msg:''
    }
}    
methods:{
    showMsg(val){
        this.msg=val
    }
}    
props / $emit 父子传值

2. $parent / $children

通过 this.$parent 或 this.$children 获取里面的数据
$parent / $children 父子传值

3. $ref

子组件标签定义 
ref="child"
父组件内使用
this.$refs.child
ref 父子传值

非父子组件通信:

1. 事件总线,利用 bus.js 传递数据,bus.$emit 与 bus.$on 传送与接收数据

// 原理上就是建立一个公共的js文件,专门用来传递消息
// bus.js     // until=>bus.js
import Vue from 'vue'
export defalult new Vue

// 在需要传递消息的地方引入
import bus from './bus.js'
// 传递消息
bus.$emit('msg',val)
// 接收消息
bus.$emit('msg',val=>{console.log(val)})
bus.js通信

2. $attrs / $listeners

1. 在父组件定义数据,data,然后在中转站绑定数据 :data="data"
2. 在中转站里定义 v-bind="$attrs"
3. 在子组件中通过 this.$attrs 接收数据
$attrs使用方法

3. vuex

4. pubsub.js 库

 

推荐阅读