Vue入门 Demo17 非父子组件间的传值
<!DOCTYPE html>
<html lang="en">
<head>
<meta content="text/html; charset=utf-8" />
<title>非父子组件间的传值(Bus/总线/发布订阅模式/观察者模式)</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
<child content="he"></child>
<child content="wen"></child>
</div>
<script>
Vue.prototype.bus = new Vue()
Vue.component('child',{
data: function(){
return {
selfContent: this.content
}
},
template: '<div @click="handleClick">{{selfContent}}</div>',
props: {
content: String
},
methods: {
handleClick: function(){
this.bus.$emit('change',this.selfContent)
}
},
mounted: function(){
var this_ = this
this.bus.$on('change', function(msg){
this_.selfContent = msg
})
}
})
var vm = new Vue({
el: "#app",
methods: {
}
})
</script>
</body>
</html>