vue中兄弟之间组件通信


我们知道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>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM