vue非父子组件间传值
通过bus实现非父子之间的传递
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>非父子组件间传值(Bus/总线/发布订阅模式/观察者模式)</title> <script src="./vue.js"></script> </head> <body> <div id="app"> <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'>{{selfContent}}</div>", methods:{ handleClick:function(){ this.bus.$emit('change',this.selfContent); } }, //实例创建后会自动触发的生命钩子 mounted:function(){ var this_ = this;
//无论点击哪个,两个组件都会触发该事件 this.bus.$on('change',function(msg){ this_.selfContent=msg; }); } }); var app = new Vue({ el:'#app' }) </script> </body> </html>