vue bus方式解决非父子组件间的传值

对于非父子组件之间的传值 通常使用VUEX 和总线等方式解决 这里我聊聊发布订阅模式(总线)

<body>
  <div class="app">
    <child content = "dell"></child> //这两个子组件之间可以互相传值
    <child content = "lee"></child>
  </div>
</body>
<script>
//每一个vue实例对象上都能访问到同一个vue实例 Vue.prototype.bus = new Vue() Vue.component("child",{ template:' <div @click="handleClick">{{selfContent}}</div>', data:function(){ return{ selfContent:this.content } }, props:{ content:{ type:String } }, methods:{ handleClick:function(){ console.log(this.selfContent)
//单击的时候 在第三方Vue实例上触发change事件并且将this.selfContent传递过去
this.bus.$emit('change',this.selfContent) } }, mounted:function(){ let this_ = this
//在页面元素渲染完成后 为第三方Vue实例 -- this.__proto__.bus 注册监听change事件
this.bus.$on('change',function(msg){ alert(0) this_.selfContent = msg }) } }) const app = new Vue({ el:'.app' })

原文地址:https://www.cnblogs.com/wangweigit3077/p/10362665.html