Vue.js 组件间通信

338 阅读3分钟

组件关系图

  • A 组件和 B 组件、B 组件和 C 组件、B 组件和 D 组件形成了父子关系
  • C 组件和 D 组件形成了兄弟关系
  • A 组件和 C 组件、A 组件和 D 组件形成了隔代关系(其中的层级可能是多级,即隔多代)

常见使用场景可以分为三类:

  • 父子组件通信: props/$emit; $parent / $children; provide / inject ; $attrs / $listeners

  • 兄弟组件通信: eventBus ; Vuex

  • 跨级通信: eventBusVuexprovide / inject$attrs / $listeners

  • 组件间传递DOM:slot插槽

父子组件之间的通信

1、props$emit

父组件通过props向子组件传递数据,子组件通过$emit向父组件传递数据。

  • 父组件向子组件传值

props 只可以从上一级组件传递到下一级组件(父子组件),即所谓的单向数据流。而且 props 只读,不可被修改,所有修改都会失效并警告。

父组件的数据通过

// App.vue  父组件
<template>
  <div id="app">
    <users :users="usersList"></users>    //前者自定义名称便于子组件调用,后者要传递数据名
  </div>
</template>
<script>

import Users from "./components/Users"  // 引入Users.vue子组件

export default {
  name: 'App',
  components:{
    "users":Users
  }
  data(){
    return{
      usersList:["Henry","Bucky","Emily"]
    }
  },
  
}
// users 子组件

<template>
  <div class="hello">
    <ul>
      <li v-for="user in users">{{user}}</li>//遍历传递过来的值,然后呈现到页面
    </ul>
  </div>
</template>
<script>
export default {
  name: 'HelloWorld',
  props:['users']  // 子组件通过props方式接受父组件的值
}
</script>
  • 子组件向父组件传值

$emit绑定一个自定义事件, 当这个语句被执行时, 就会将参数arg传递给父组件,父组件通过v-on监听并接收参数。

// 父组件中  
<template>  
  <div class="section">  
    <com-article :articles="articleList" @onEmitIndex="onEmitIndex"></com-article>  
    <p>{{currentIndex}}</p>  
  </div>  
</template>  
<script>  
import comArticle from './test/article.vue'  
export default {  
  name: 'HelloWorld',  
  components: { comArticle },  
  data() {  
    return {  
      currentIndex: -1,  
      articleList: ['红楼梦', '西游记', '三国演义']  
    }  
  },  
  methods: {  
    onEmitIndex(index) {  
      this.currentIndex = index  
    }  
  }  
}  
</script>  

// 子组件
<template>  
  <div>  
    <div v-for="(item, index) in articles" :key="index" @click="emitIndex(index)">{{item}}</div>  
  </div>  
</template>  
<script>  
export default {  
  props: ['articles'],  
  methods: {  
    emitIndex(index) {  
        
      //  通过$emit向父组件传递一个onEmitIndex方法,
      //  index是单一的参数。(参数也可以是多个,已‘,’分隔开)
      this.$emit('onEmitIndex', index)
    }  
  }  
}  
</script>

2、$children / $parent

通过$parent$children就可以访问组件的实例。

// 父组件中  
<template>  
  <div class="hello_world">  
    <div>{{msg}}</div>  
    <com-a></com-a>  
    <button @click="changeA">点击改变子组件值</button>  
  </div>  
</template>  
<script>  
import ComA from './test/comA.vue'  
export default {  
  name: 'HelloWorld',  
  components: { ComA },  
  data() {  
    return {  
      msg: 'Welcome'  
    }  
  },  
  methods: {  
    changeA() {  
      // 获取到子组件A  
      this.$children[0].messageA = 'this is new value'  
    }  
  }  
}  
</script>  
// 子组件中  
<template>  
  <div class="com_a">  
    <span>{{messageA}}</span>  
    <p>获取父组件的值为:  {{parentVal}}</p>  
  </div>  
</template>  
<script>  
export default {  
  data() {  
    return {  
      messageA: 'this is old'  
    }  
  },  
  computed:{  
    parentVal(){  
      return this.$parent.msg;  
    }  
  }  
}  
</script> 

3、$ref$parent

1:父组件调用子组件时,定义一个ref
<child ref="child"></child>
2、父组件里调用
this.$refs.child.属性
this.$refs.child.方法
3、子组件里调用父组件
this.$parent.属性
this.$parent.方法

兄弟组件通信

eventBus

eventBus 又称为事件总线,在vue中可以使用它来作为沟通桥梁的概念, 就像是所有组件共用相同的事件中心,可以向该中心注册发送事件或接收事件, 所以组件都可以通知其他组件。

步骤如下:

  1. 初始化: 创建一个事件总线并将其导出, 以便其他模块可以使用或者监听它。
// event-bus.js  
import Vue from 'vue'  
export const EventBus = new Vue() 

另一种方式,直接在项目中的main.js初始化EventBus.(全局的事件总线)

//main.js
Vue.prototype.$EventBus = new Vue()

2.发送事件

EventBus.$emit(channel:string,callback(payload1,...))

组件A用this.Bus.$emit('eventName', value)触发事件, 发送数据,第一个参数是发送数据的名称,接收时还用这个名字接收,第二个参数是这个数据现在的位置。

组件B用this.Bus.$on('eventName', value => { this.print(value) })接收事件。接收数据,第一个参数是数据的名字,与发送时的名字对应,第二个参数是一个方法,要对数据的操作。

假设你有两个组件: additionNum 和 showNum, 这两个组件可以是兄弟组件也可以是父子组件。

兄弟组件为例:

<template>  
  <div>  
    <show-num-com></show-num-com>  
    <addition-num-com></addition-num-com>  
  </div>  
</template>  
<script>  
import showNumCom from './showNum.vue'  
import additionNumCom from './additionNum.vue'  
export default {  
  components: { showNumCom, additionNumCom }  
}  
</script> 
// addtionNum.vue 中发送事件  
<template>  
  <div>  
    <button @click="additionHandle">+加法器</button>      
  </div>  
</template>  
<script>  
import {EventBus} from './event-bus.js'  
console.log(EventBus)  
export default {  
  data(){  
    return{  
      num:1  
    }  
  },  
  methods:{  
    additionHandle(){  
      EventBus.$emit('addition', {  
        num:this.num++  
      })  
    }  
  }  
}  
</script> 

3.接收事件

EventBus.$on(channel:string,callback(payload1,...))
// showNum.vue 中接收事件  
<template>  
  <div>计算和: {{count}}</div>  
</template>  
<script>  
import { EventBus } from './event-bus.js'  
export default {  
  data() {  
    return {  
      count: 0  
    }  
  },  
  mounted() {  
    EventBus.$on('addition', param => {  
      this.count = this.count + param.num;  
    })  
  }  
}  
</script>

4.移除事件监听者

import { eventBus } from 'event-bus.js'  
EventBus.$off('addition', {}) 

手写eventBus的原理

class eventBus {
    constructor (){
       this.eventMap = {}
    }
    addEventListener(eventName,fn,isOnce){
       const taskObj = {fn,isOnce};
       if(!this.eventMap[eventName]){
          this.eventMap[eventName] = [taskObj]
       }else {
          this.eventMap[eventName].push(taskObj)
       }
    }
    // on方法作用是挂载事件。
    on(eventName,fn){
       this.addEventListener(eventName,fn,false)
    }
    // once挂载的事件只触发一次。
    once(eventName,fn){
       this.addEventListener(eventName,fn,true)
    }
    // off是移除事件的方法。
    off(eventName){
       this.eventMap(eventName) = []
    }
    // trigger是触发事件的方法。
    trigger(eventName){
       const tasks = this.eventMap[eventName]
       const onceTasks = []
       tasks && tasks.forEach((item,index)=>{
          const {fn,isOnce} = item;
          fn && fn();
          if(isOnce){
             onceTasks.push(index)
          }
       })
       onceTasks.forEach((index)=>{
          this.eventMap[eventName].splice(index,1)
       })
    }
}

Vuex实现组件间的通信

Vuex实例应用:

// 父组件  
<template>  
  <div id="app">  
    <ChildA/>  
    <ChildB/>  
  </div>  
</template>  
<script>  
  import ChildA from './components/ChildA' // 导入A组件  
  import ChildB from './components/ChildB' // 导入B组件  
  export default {  
    name: 'App',  
    components: {ChildA, ChildB} // 注册A、B组件  
  }  
</script>  

// 子组件childA  
<template>  
  <div id="childA">  
    <h1>我是A组件</h1>  
    <button @click="transform">点我让B组件接收到数据</button>  
    <p>因为你点了B,所以我的信息发生了变化:{{BMessage}}</p>  
  </div>  
</template>  
<script>  
  export default {  
    data() {  
      return {  
        AMessage: 'Hello,B组件,我是A组件'  
      }  
    },  
    computed: {  
      BMessage() {  
        // 这里存储从store里获取的B组件的数据  
        return this.$store.state.BMsg  
      }  
    },  
    methods: {  
      transform() {  
        // 触发receiveAMsg,将A组件的数据存放到store里去  
        this.$store.commit('receiveAMsg', {  
          AMsg: this.AMessage  
        })  
      }  
    }  
  }  
</script>  
// 子组件 childB  
<template>  
  <div id="childB">  
    <h1>我是B组件</h1>  
    <button @click="transform">点我让A组件接收到数据</button>  
    <p>因为你点了A,所以我的信息发生了变化:{{AMessage}}</p>  
  </div>  
</template>  
<script>  
  export default {  
    data() {  
      return {  
        BMessage: 'Hello,A组件,我是B组件'  
      }  
    },  
    computed: {  
      AMessage() {  
        // 这里存储从store里获取的A组件的数据  
        return this.$store.state.AMsg  
      }  
    },  
    methods: {  
      transform() {  
        // 触发receiveBMsg,将B组件的数据存放到store里去  
        this.$store.commit('receiveBMsg', {  
          BMsg: this.BMessage  
        })  
      }  
    }  
  }  
</script> 

vuex的store,js

import Vue from 'vue'  
import Vuex from 'vuex'  
Vue.use(Vuex)  
const state = {  
  // 初始化A和B组件的数据,等待获取  
  AMsg: '',  
  BMsg: ''  
}  
const mutations = {  
  receiveAMsg(state, payload) {  
    // 将A组件的数据存放于state  
    state.AMsg = payload.AMsg  
  },  
  receiveBMsg(state, payload) {  
    // 将B组件的数据存放于state  
    state.BMsg = payload.BMsg  
  }  
}  
export default new Vuex.Store({  
  state,  
  mutations  
}) 

隔代组件间的通信

如上图,A组件是如何给D组件通信的?

  • 使用props绑定来进行一级一级的信息传递, 如果D组件中状态改变需要传递数据给A, 使用事件系统一级级往上传递。

  • 使用eventBus,这种情况下还是比较适合使用, 但是碰到多人合作开发时, 代码维护性较低, 可读性也低。

  • 使用Vuex来进行数据管理, 但是如果仅仅是传递数据, 而不做中间处理,使用Vuex处理感觉有点大材小用了。

//  父组件 index.vue  
<template>  
 <div>  
   <child-com1  
     :name="name"  
     :age="age"  
     :gender="gender"  
     :height="height"  
     title="程序员成长指北"  
   ></child-com1>  
 </div>  
</template>  
<script>  
const childCom1 = () => import("./childCom1.vue");  
export default {  
 components: { childCom1 },  
 data() {  
   return {  
     name: "zhang",  
     age: "18",  
     gender: "女",  
     height: "158"  
   };  
 }  
};  
</script>  
// 子组件 childCom1.vue  
<template class="border">  
 <div>  
   <p>name: {{ name}}</p>  
   <p>childCom1的$attrs: {{ $attrs }}</p>  
   <child-com2 v-bind="$attrs"></child-com2>  
 </div>  
</template>  
<script>  
const childCom2 = () => import("./childCom2.vue");  
export default {  
 components: {  
   childCom2  
 },  
 inheritAttrs: false, // 可以关闭自动挂载到组件根元素上的没有在props声明的属性  
 props: {  
   name: String // name作为props属性绑定  
 },  
 created() {  
   console.log(this.$attrs);  
    // { "age": "18", "gender": "女", "height": "158", "title": "程序员成长指北" }  
 }  
};  
</script>  
// childCom2.vue  
<template>  
 <div class="border">  
   <p>age: {{ age}}</p>  
   <p>childCom2: {{ $attrs }}</p>  
 </div>  
</template>  
<script>  
export default {  
 inheritAttrs: false,  
 props: {  
   age: String  
 },  
 created() {  
   console.log(this.$attrs);   
   // { "gender": "女", "height": "158", "title": "程序员成长指北" }  
 }  
};  
</script> 

provide inject

父组件中通过provide来提供变量,子组件中通过inject来注入变量。

⚠️:不论子组件嵌套有多深,只要调用了inject就可以注入provide中的数据,而不是局限于只能从当前父组件的props属性中回数据

🌰: 假设有三个组件:A.vue、B.vue、C.vue,其中C是B的子组件,B是A的子组件。

// A.vue
<comB></comB>
provide:{
for:'demo'
}

// B.vue
{{demo}}
<comC></comC>
inject:['for']
data(){
  return {
    demo:this.for
  }
}
// C.vue
{{demo}}
inject:['for']
data(){
  return {
    demo:this.for
  }
}

组件间传递DOM节点,使用slot插槽

父子组件 props与$emit详解

// 定义子组件
<template>
    {{age}}
    <button @click="send">传值给父组件</button>
</template>
export default{
// 子组件通过props定义该变量来接受参数,还可以指定该变量的类型和默认值
  props:{
     age:{type:Number}
  },
  methods:{
     send(){
       this.$emit('sendMsg',{age:this.age})  // 子组件通过this.$emit()传值
     },
     printAge(age){
       console.log(age)
     }
  }
}
// 定义父组件
<template>
   // 父组件通过监听子函数中事件名称来接收参数
  <child @sendMsg="process" :age="myAge" ref="child"/>  // 父组件通过v-bind来传递参数,简写未:age="myAge",意思是把myAge绑定到age上
  
</template>
import Child
export default{
  components:{
    Child
  },
  data(){
    return {
      myAge:''
    }
  },
  methods:{
   // 接收子组件参数
   process(obj){
      console.log(obj)
   },
   // 调用子组件方法,动态传参
   invokenChildMethod(age){
      this.$refs.child.printAge(age)
   }
  }
}