Vue兄弟组件通讯

初级开发的面试中经常会被问到Vue的组件通讯方法,除了父传子的props、子传父的emit,Vue也支持兄弟组件之间通讯。实现兄弟组件通讯的核心是 vm.$emit、vm.$on、vm.$off,为了照顾小白,这里多提一嘴,vm代表vue实例,你会在官方文档上大量看到这个关键字哦!

下面开始操作:

1. 创建 Vue 实例,这里有两种方式,可以新建个独立的js文件导出实例,也可以在Vue的prototype原型上挂载一个实例,博主更喜欢后者

# 新建 bus.js
import Vue from 'vue'
export default new Vue()
# 写在 main.js 里

Vue.prototype.$bus = new Vue()
...
new Vue({
  render: function (h) { return h(App) },
}).$mount('#app')

2. 搭建兄弟组件的环境

# App.vue 里
<template>
  <div>
    <InfoComp />
    <MsgComp />
  </div>
</template>

<script>
import InfoComp from '@/components/info-comp.vue'
import MsgComp from '@/components/msg-comp.vue'
...
</script>

3. 在任一兄弟组件内使用 $emit 创建自定义事件,同时携带值

# info-comp 组件里
<template>
  <div>
    <input type="text" v-model="info" @change="handleEmit" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      info: ''
    }
  },
  methods: {
    handleEmit() {
      this.$bus.$emit('sendBrother', this.info)
    }
  }
}
</script>

4. 在另一个兄弟组件内使用 $on 监听自定义事件获取值,并在恰当的时机使用 $off 销毁 

# msg-comp 组件里
<template>
  <div>
    <h2>{
   
   { msg }}</h2>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: ''
    }
  },
  methods: {
    getBrother(info) {
      this.msg = info
    }
  },
  mounted () {
    this.$bus.$on('sendBrother', this.getBrother)
  },
  beforeDestroy () {
    // 及时销毁, 避免造成内存泄漏
    this.$bus.$off('sendBrother', this.getBrother)
  }
}
</script>

是不是超简单?博主可是写了很久呢,对你有帮助的话不要忘了一键三连哟。

扫描二维码关注公众号,回复: 17046504 查看本文章

End-----------------------

猜你喜欢

转载自blog.csdn.net/u011690675/article/details/130268979
今日推荐