自定义全局变量在uniapp的Vuex应用

       本文介绍了uniapp使用自定义全局变量的方法。当同一业务在连续页面操作时,存在部分筛选变量需要始终保持一致,比如时间筛选条件等,来回跳转页面时如果采用变量传递,常较为繁琐,存在遗漏传递或未清除上一次变量值,造成错误。本文介绍了通过store本地缓存机制,实现全局变量的方法。

一、自定义全局变量设置文件businessGlobeVariable.js

@/store/modules/businessGlobeVariable

解释:

state:  自定义变量(本地缓存变量数据)

mutation: 数据修改

action:异步操作,调用mutation里的方法,从而修改state缓存数据

getters: 读取state数据


const businessGlobeVariable = {
    namespaced: true,
    state: {
        // 日常点检
        timeRangeTypeCheckDaily: '',
        // 周期巡视
        timeRangeTypeInspectionDaily: '',
    },
    mutations:{
        SET_TIME_RANGE_TYPE_CHECK_DAILY: (state, timeRangeTypeCheckDaily) => {
            state.timeRangeTypeCheckDaily = timeRangeTypeCheckDaily
        },
        SET_TIME_RANGE_TYPE_INSPECTION_DAILY: (state, timeRangeTypeInspectionDaily) => {
            debugger
            state.timeRangeTypeInspectionDaily = timeRangeTypeInspectionDaily
        },
    },
    actions:{
        SetTimeRangeTypeCheckDaily({ commit }, timeRangeTypeCheckDaily) {
            commit('SET_TIME_RANGE_TYPE_CHECK_DAILY', timeRangeTypeCheckDaily);
        },
        SetTimeRangeTypeInspectionDaily({ commit }, timeRangeTypeInspectionDaily) {
            debugger
            commit('SET_TIME_RANGE_TYPE_INSPECTION_DAILY', timeRangeTypeInspectionDaily);
        },
    },
    getters: {
        timeRangeTypeCheckDaily: state => state.timeRangeTypeCheckDaily,
        timeRangeTypeInspectionDaily: state => state.timeRangeTypeInspectionDaily,
    }
}
export default businessGlobeVariable

二、缓存变量管理文件

@/store/index.js

import businessGlobeVariable from '@/store/modules/businessGlobeVariable'



const store = new Vuex.Store({
  modules: {
    user,
    businessGlobeVariable
  },

......

})

三、使用

(1)设置全局变量

调用mutation方法并传参

this.$store.dispatch('businessGlobeVariable/SetTimeRangeTypeCheckDaily','lastThreeMonths')

(2)读取全局变量

Let e = this.$store.getters['businessGlobeVariable/timeRangeTypeCheckDaily']

你可能感兴趣的:(uniapp,vue,前端,uniapp,uni-app)