<head>
<meta charset="utf-8" />
<title>非父子组件之间的传值(Bus/总线、发布订阅模式、观察者模式)</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<child content="Dell"></child>
<child content="Lee"></child>
</div>
<script>
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: function () {
// console.log(this.content)
this.bus.$emit('change',this.selfContent)
}
},
mounted: function () {
var _this=this
//监听change事件
this.bus.$on('change', function (msg) {
console.log(msg)
_this.selfContent=msg
})
}
})
var vm = new Vue({
el: "#root",
})
</script>
</body>
</html>
原始状态
点击后改变兄弟组件的内容