引言:
非父子之间,
该怎么传值呢
非父子之间传值
使用总线机制,来给他们传值
这里用一个兄弟组件的例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| <body> <div id="root"> <child content="Dell"></child> <child content="Lee"></child> </div>
<script> Vue.prototype.bus = new Vue()
Vue.component('child',{ data(){ return { selfContent: this.content } }, props:{ content: String }, template:'<div @click="handleClick">{{selfContent}}</div>', methods:{ handleClick(){ this.bus.$emit('change',this.content) } }, mounted(){ var this_ = this; this.bus.$on('change',function(msg){ this_.selfContent = msg }) } })
var vm = new Vue({ el:'#root' }) </script> </body>
|