vue2.0 监听全局参数的变化

Posted 久天.

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue2.0 监听全局参数的变化相关的知识,希望对你有一定的参考价值。

背景

由于一个详情页面的功能比较多,拆分为上下多级的很多组件,当一个组件中编辑修改后,需要触发操作记录组件调用接口,更新视图

一,vuex 声明全局变量

store/modules/actionLog.ts

import { VuexModule, Module, Mutation, Action, getModule } from 'vuex-module-decorators'
import store from '@/store'

export interface ILog {
  actionLogArr: Array<string>
}

// 当详情组件点击了编辑模块确认按钮,就需要调用操作记录接口
@Module({ name: 'ActionLog', dynamic: true, store, })
class ActionLog extends VuexModule implements ILog {
  public actionLogArr: Array<string> = []
  @Mutation
  public SET_ACTION_LOG(item: string) {
    this.actionLogArr.push(item)
  }
  // getter
  get getActionLogArr(): Array<string> {
    return this.actionLogArr
  }
}

export const ActionLogModule = getModule(ActionLog)

store/index.ts

import Vue from 'vue'
import Vuex from 'vuex'

import createPersistedState from 'vuex-persistedstate'
import { ILog } from './modules/resumeActionLog'

Vue.use(Vuex)

export interface IRootState {
  actionLog: ILog
}

export default new Vuex.Store<IRootState>({
  plugins: [createPersistedState({
    storage: window.sessionStorage
  })]
})

二,在组件中修改提交数据

// 引入
import { ActionLogModule } from '@/store/modules/actionLog'

// 使用
ActionLogModule.SET_ACTION_LOG('update')

三,在组件中监听这个数据的变化

import { ActionLogModule } from '@/store/modules/actionLog'
// 当其他组件模块有操作,就会调用操作记录接口,达到实时变化更新的效果
get logArr() {
   return ActionLogModule.getActionLogArr
}
@Watch('logArr')
private logArrWatch(newVal: any) {
 console.log('参数改变了:',newVal)
 this.findActionLog()
}

 

以上是关于vue2.0 监听全局参数的变化的主要内容,如果未能解决你的问题,请参考以下文章

vue2.0有哪些变化

vue2.0之监听属性的使用心得及搭配计算属性的使用

vue2.0 全局变量怎么设置

vue2.0 代码功能片段

vue2.0学习笔记之组件

☀️Vue2.0为什么不能检查数组的变化?又该如何解决?