vue中组件通信(父子组件, 爷孙组件, 兄弟组件)

版权声明: https://blog.csdn.net/Helloyongwei/article/details/82384551

vue中我们常常用到组件. 那么组件总体可以分为如下的几种关系.
父子组件, 爷孙组件, 兄弟组件. 这几种组件之间是如何通信的呢?

父子组件通信

根据vue中的文档可知, 组件的props属性用于接收父组件传递的信息. 而子组件想要向父组件传递信息, 可以使用$emit事件.
我们定义两个组件, 一个为父组件名为father, 另外一个为子组件child. 子组件通过props属性接收父组件传递的值, 这个值为fname, 是父组件的名字. 点击子组件的按钮, 触发toFather事件, 向父组件传递消息. 父组件做出相应的反应.
将父组件和子组件放入名为app的vue实例中

Vue.component('child', {
  props: ['fname'],
  template: `
    <div class="child">
      这是儿子, 我爸爸是{{fname}}
      <button @click="$emit('toFather')">点我通知爸爸</button>
    </div>
  `
})

Vue.component('father', {
  data() {
    return {
      info: '无消息'
    }
  },
  template: `
    <div class="father">
      这是父亲, {{info}}
      <child fname="father" @toFather="getSonMsg"></child>
    </div>
  `,
  methods: {
    getSonMsg() {
      this.info = '我收到儿子传来的消息了'
    }
  }
})
new Vue({
  el: '#app',
})

注意上面的组件定义顺序不能换
让后我们在html文件中写入即可

<div id="app">
    <father></father>
  </div>

点击子组件的按钮
点击按钮后发现我们的父组件发生了变化
父组件接收子组件的消息
点击这里可以查看效果

爷孙组件通信

因为vue只是说明了父子组件如何通信, 那么爷孙组件是没有办法直接通信的. 但是它们可以分解为两个父子组件通信.
即爷爷和父亲看成是一个父子组件, 而父亲和孙子看成是一个父子组件. 这样它们之间就可以进行通信了. 通过父亲组件合格桥梁, 可以实现爷孙的通信. (注意: 爷孙组件是无法直接通信的)

兄弟组件通信

兄弟组件通信即组件之间通信. 这就要用到观察者模式了. 因为vue实例的原型全部来自Vue.prototype. 那么我们就可以了将事件中心绑定到Vue.prototype的某个属性上, 暂且叫它为bus吧.

let bus = new Vue()
Vue.prototype.bus = bus

我们再定义两个组件, up组件和down组件, 当点击down组件中的按钮时, 会给up组件传递信息.

Vue.component('up', {
  data() {
    return {
      msg: '未传递消息'
    }
  },
  template: `
    <div class="up">
      <p>这是up组件, 下一行为down传递的消息</p>
      <p>{{msg}}</p>
    </div>
  `,
  mounted() {
    this.bus.$on('send', (msg)=> {
      this.msg = (msg)
    })
  }
})

Vue.component('down', {
  template: `
    <div class="down">
      <p>这是down</p>
      <button @click="toUp">点击我向up组件传递消息</button>
    </div>
  `,
  methods: {
    toUp() {
      this.bus.$emit('send', 'down来消息了')
    }
  }
})
new Vue({
  el: '#app',
})

并且将两个组件放入名为app的实例中

<div id="app">
    <up></up>
    <down></down>
  </div>

点击down按钮
按钮被点击后, up组件会接收到消息
up消息改变

点击这里查看源代码

猜你喜欢

转载自blog.csdn.net/Helloyongwei/article/details/82384551