<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>非父子组件之间的传值(BUS/总线/发布订阅者模式/观察者模式)</title>
</head>
<body>
<div id="app">
<child content="zhang"></child>
<child content="san"></child>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.prototype.bus = new Vue();
Vue.component('child',{
props: ['content'],
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',
methods: {
handleClick: function () {
alert('click');
}
}
});
</script>
</html>