<body>
<div id="app">
<child content="Dean"></child>
<child content="Wade"></child>
</div>
<script>
Vue.component('child', {
props: {
content: String
},
template: '<div>{
{content}}</div>'
})
var vm = new Vue({
el: '#app',
data: {
},
methods: {
handleClick() {
console.log('root component clicked!')
}
}
});
</script>
</body>
我们想实现,通过点击上面的Dean,把下面的Wade改成Dean,点击下面的Wade,上面的Dean会变成Wade。这样的需求涉及到非父子组件间传值
<body>
<div id="app">
<child content="Dean"></child>
<child content="Wade"></child>
</div>
<script>
// 挂载到Vue的原型上
Vue.prototype.bus = new Vue()
Vue.component('child', {
data: function(){
return {
selfContent: this.content
}
},
props: {
content: String
},
template: '<div @click="handleClick">{
{selfContent}}</div>',
methods: {
handleClick() {
// 点击把自己的值传递给另一个组件
this.bus.$emit('change', this.content)
}
},
mounted: function() {
var this_ = this
console.log('this_:', this_)
this.bus.$on('change', function(msg){
this_.selfContent = msg
})
}
})
var vm = new Vue({
el: '#app',
data: {
}
});
</script>
</body>
注意这里的this的含义:指向每个组件自身
还有就是为什么要保存this_ = this