Vue中兄弟组件间传值-(Bus/总线/发布订阅模式/观察者)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="root">
<child content="Nay"></child>
<child content="Ek"></child>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
Vue.prototype.bus = new Vue()
Vue.component('child', {
data() {
return {
selfContent : this.content
}
},
props: {
content: String
},
template: '<div @click="handleClick">{{selfContent}}</div>',
methods: {
handleClick() {
this.bus.$emit('change', this.selfContent)
}
},
mounted() {
// var that = this
// this.bus.$on('change', function(msg) {
// 这里this的指向发生了变更所以需要提前保存this,或者用箭头函数解决
// that.content = msg
// })
this.bus.$on('change', (msg) => {
this.selfContent = msg
})
}
})
var vm = new Vue({
el: '#root'
})
</script>
</body>
</html>
今天你学习了吗!!!