import Vue from 'vue'; export const EventBus = new Vue();
界面使用:
<template>
<div>数据
<div class="pleeease-click-me" @click="emitGlobalClickEvent()">啦啦啦</div>
</div>
</template>
<script>
// Import the EventBus we just created.
import { EventBus } from '../vuex/event-bus.js';
export default {
data(){
return {
clickCount: 0
}
},
methods: {
emitGlobalClickEvent() {
this.clickCount++;
// Send the event on a channel (i-got-clicked) with a payload (the click count.)
EventBus.$emit('i-got-clicked', this.clickCount);
}
}
}
</script>
<style scoped>
</style>
另一个监听:
<template>
<div>列表 {{count}}
<button @click="$store.commit('add')">点击</button>
<button @click="add()">页面点击</button>
<p>{{x}}</p>
</div>
</template>
<script>
// Import the EventBus.
import { EventBus } from '../vuex/event-bus.js';
export default {
name: "list",
data(){
return{
x: ""
}
},
created(){
// Listen for the i-got-clicked event and its payload.
EventBus.$on('i-got-clicked', clickCount => {
console.log(222222)
});
},
mounted(){
},
computed:{
count:function(){
return this.$store.state.count // 读取vuex的值
}
},
methods: {
add(){
this.$store.dispatch("add")
}
}
}
</script>
<style scoped>
</style>