1. 程式人生 > >vue中兄弟之間組件通信

vue中兄弟之間組件通信

http 組件通信 .net container 項目 containe turn eth cli

我們知道Vue中組件之間的通信有很多方式,父子之間通信比較簡單,當我們使用vuex時候,兄弟組件之間的通信也很好得到解決

當我們項目較小時候,不使用vuex時候Vue中兄弟組件之間的通信是怎樣進行的呢

參考鏈接:https://my.oschina.net/u/3229305/blog/1820279

//在生成vue實例前,給Vue的原型上添加一個bus屬性,這個屬性是vue的實例,
//之後創建的vue實例都具有bus這個屬性
//首先在main.js
 Vue.prototype.bus = new Vue();

//組件hello

<template>
  <div class="container">
    <button @click="handler">hello word</button>
    <word></word>
  </div>
</template>
<script>
  import word from ‘./word.vue‘
  export default{
    methods:{
      handler () {
        this.$bus.$emit(‘shareText‘, ‘hello word‘)
      }
    }
  }
</script>

// 組件world
<template>
  <div class="con">
    {{text}}
  </div>
</template>
<script>
export default {
  data () {
    return {
      text: ‘hello‘
    }
  },
  mounted () {
    var that = this
    this.$bus.$on(‘shareText‘, function (text) {
      that.text = text
    })
  }

}
</script>

vue中兄弟之間組件通信