我们写一个例子演示一下,点击A下面的按钮时,B数字+1,点击B下面的按钮时,A数字+10:
<body>
<div id="app">
<test-a></test-a>
<test-b></test-b>
</div>
<script>
// 事件中心
var hub = new Vue()
// 组件a
Vue.component('test-a', {
data: function () {
return {
num: 0
}
},
template: `
<div>
<div>A:{{ num }}</div>
<div>
<button @click="handle">Click</button>
</div>
</div>
`,
methods: {
// 触发事件
handle: function () {
hub.$emit('b-plus', 1)
}
},
mounted: function () {
// 监听事件
hub.$on('a-plus', (val) => {
this.num += val
})
}
})
// 组件b
Vue.component('test-b', {
data: function () {
return {
num: 0
}
},
template: `
<div>
<div>B:{{ num }}</div>
<div>
<button @click="handle">Click</button>
</div>
</div>
`,
methods: {
// 触发事件
handle: function () {
hub.$emit('a-plus', 10)
}
},
mounted: function () {
// 监听事件
hub.$on('b-plus', (val) => {
this.num += val
})
}
})
var vm = new Vue({
el: '#app',
data: {
},
methods: {
}
})
</script>
</body>