vuejs非父子组件传值
当父组件要给孙子,或者孙子与孙子要传值的时候怎么传,一层一层传太麻烦了,vuejs提供了一中模式叫发布订阅模式(观察者模式,bus,总线)来处理非父子组件间的传值
<div id='root'> <child content = 'Dell'></child> <child content = 'Lee'></child> </div> <script> Vue.prototype.bus = new Vue(); Vue.component('child',{ props:{ content:String }, data:function(){ return { selfContent:this.content } }, template:'<div @click="handleClick">{{this.selfContent}}</div>', methods:{ handleClick:function(){ this.bus.$emit('change',this.selfContent) } }, mounted:function(){////页面已经被渲染完毕了的时候被执行 var that = this; this.bus.$on('change',function(msg){ that.selfContent = msg; }) } }) var vm = new Vue({ el:'#root', methods:{ handleClick:function(){ alert(1); } } }) </script>