1. 定义全局事件触发器 event-emitter.js
- /* 事件触发器 */
-
- class EventEmitter {
- constructor() {
- this.subs = Object.create(null) // 对象没有 原型属性 提高性能
- }
-
- // 注册事件
- $on(eventType, handler) {
- this.subs[eventType] = this.subs[eventType] || []
- this.subs[eventType].push(handler)
- }
- //触发事件
- $emit(eventType) {
- if (this.subs[eventType]) {
- this.subs[eventType].forEach(handler => {
- handler()
- })
- }
- }
- }
-
- const em = new EventEmitter()
-
- export default em
2. 引用事件触发器 main.js
- import EventEmitter from '@/utils/event-emitter'
-
- /* 全局事件 */
- Vue.prototype.$eventEmitter = EventEmitter
3. 在需要的地方进行事件 绑定
- // 加载的时候进行绑定
- mounted() {
- /* 绑定 刷新待办信息 */
- //this.$eventEmitter.$on('refreshCheckwait', this.getCheckwait)
-
- /* 绑定 notice 列表 */
- this.$eventEmitter.$on('refreshNotice', this.getNewMessage)
- },
-
-
-
- // 声明方法, 供绑定的事件调用
- methods: {
-
- // 获取最新消息
- getNewMessage(){
- messageApi.getList({ ...this.messageSearchption }).then(res=>{
- const data = res.data.data
- if(data) this.noReadNum = data.noReadNum
-
- }).catch(err=>{console.log(err);})
- },
-
-
- }
4. 调用: 全局绑定事件 和 使用
- // 请求后台接口后,刷新绑定的全局事件,调用方法。进行数据更新
- checkApi.save(params).then(res => {
- const data = res.data
- if(data.success) {
- this.$notify({
- title: '成功',
- message: '提交成功',
- type: 'success'
- })
- this.$eventEmitter.$emit('refreshCheckwait')
- this.$router.push({name: 'qjapproval-page'})
- } else {
- this.$notify({
- title: '失败',
- message: '提交失败',
- type: 'error'
- })
- }
- this.submitLoading = false
- }).catch(err => this.submitLoading = false)
需求如图:因为这两个不存在组件关系,所以我们使用Vuex来解决这个实时刷新

1.首先在vuex的state定义数据如下
- state{
-
- noticeCount: 0,
-
- }
2.更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数,在通过mutation更新数据的时候, 有可能我们希望携带一些额外的参数,你可以向 store.commit 传入额外的参数
- //noticeCount额外的参数
-
- SET_NOTICE_COUNT: (state, noticeCount) => {
-
- console.log("noticeCount", noticeCount);
-
- state.noticeCount = noticeCount;
-
- },
3.因为我们的接口请求数据只能放在action异步请求这里,为何把接口数据放在vuex呢?因为你可能这个铃铛数量的改变是多个页面影响的。
- actions: {
-
- getUnreadMessagesCount({ commit }) {
-
- inventoryNotice.getInventoryCount().then((res) => {
- //异步获取到铃铛的数量, 触发mutations的方法 把值赋给noticeCount
- commit("SET_NOTICE_COUNT", res.data.data);
- });
-
- },
-
- },
4.接下来vuex的工作都准备好了,接下来在你需要操作的页面点击按钮事件那里调用action的方法
this.$store.dispatch("getUnreadMessagesCount");//调用vuex里面的异步方法 请求获取到铃铛的数量
5.最后在铃铛页面使用监听属性(computed)拿到数据
- import { mapState } from "vuex";
-
-
-
- computed:{
-
- ...mapState({
-
- count: (state) => state.common.noticeCount, //直接拿到count数量
-
- })
-
- }
至此利用vuex进行实时刷新的消息通知数量的功能已完成。有疑问的小伙伴可以多交流沟通