非父子组件间的传值,使用Bus/总线/发布订阅模式/观察者模式
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>非父子组件间的传值(Bus/总线/发布订阅模式/观察者模式)</title>
<script src="./vue.js"></script>
<style>
</style>
</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="hadnleClick">{{content}}</div>',
methods: {
hadnleClick: function() {
this.bus.$emit('change', this.content);
}
},
mounted: function() {
var this_ = this
this.bus.$on('change', function(msg) {
this_.content = msg;
})
}
})
var app = new Vue({
el: " #root ",
data: {
},
})
</script>
</body>
</html>
以上代码会发生一个错误,原因是强制改变了content.
我们使用slefContent:this.content来处理
data: function() {
return {
selfContent: this.content
}
},
完整正确的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>非父子组件间的传值(Bus/总线/发布订阅模式/观察者模式)</title>
<script src="./vue.js"></script>
<style>
</style>
</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="hadnleClick">{{selfContent}}</div>',
methods: {
hadnleClick: 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: " #root ",
data: {
},
})
</script>
</body>
</html>