Value passing between non-parent and child components
To achieve, I click the top one, the bottom one will change, and click the bottom one and the top one will change accordingly.
Vue.prototype.bus = new Vue() 挂载一个bus
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</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() {
this.bus.$emit('change', this.selfContent)
}
},
mounted: function() {
var this_ = this
<!--绑定bus里的监听事件$on-->
this.bus.$on('change', function(msg) {
this_.selfContent = msg
})
}
})
var vm = new Vue({
el: '#root'
})
</script>
</body>
</html>