vuex持久化和模块化写法记录

一、vuex持久化

1、使用插件vuex-persistedstate  Vuex数据持久化存储

2、不使用插件方式:存储在localStorage或者sessionStorage,state定义变量,mutations同步更新变量,并且存储一份在localStorage或者sessionStorage中,actions异步请求,触发mutations同步更新,getters(store的计算属性getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算)对state进行计算并缓存。

// import { findMenuTree, findMenuList } from "../../json/list";  // 测试环境,暂时使用
// import { findMenuList } from "../../json/list";  // 测试环境,暂时使用
import { findMenuTreeSideBar, findMenuList } from '@/http/moudules/menu'
import { getPermissionList } from '@/http/moudules/login'

export default {
  state: {
    menuTree: null, // 菜单树
    menuList: null,
    firstPath: null,
    menuRouteLoaded: null // 菜单和路由是否已经加载
  },
  getters: {
    menuTree: (state) => {
      if (state.menuTree === null || state.menuTree.length === 0) {
        state.menuTree = JSON.parse(sessionStorage.getItem('menuTree')) || []
      }
      return state.menuTree
    },
    menuList: (state) => {
      if (state.menuList === null || state.menuList.length === 0) {
        state.menuList = JSON.parse(sessionStorage.getItem('menuList')) || []
      }
      return state.menuList
    },
    firstPath: (state) => {
      if (state.firstPath === null) {
        state.firstPath = sessionStorage.getItem('firstPath') || '/'
      }
      return state.firstPath
    },
    menuRouteLoaded: (state) => {
      if (state.menuRouteLoaded === null) {
        state.menuRouteLoaded = sessionStorage.getItem('menuRouteLoaded') || false
      }
      return state.menuRouteLoaded
    }
  },
  mutations: {
    setMenuTree(state, menuTree) {
      // 设置导航菜单树
      sessionStorage.setItem('menuTree', JSON.stringify(menuTree))
      state.menuTree = menuTree
    },
    setMenuList(state, menuList) {
      // 设置菜单列表
      sessionStorage.setItem('menuList', JSON.stringify(menuList))
      state.menuList = menuList
    },
    setFirstPath(state, firstPath) {
      sessionStorage.setItem('firstPath', firstPath)
      state.firstPath = firstPath
    },
    setMenuRouteLoaded(state, menuRouteLoaded) {
      // 改变菜单和路由的加载状态
      sessionStorage.setItem('menuRouteLoaded', menuRouteLoaded)
      state.menuRouteLoaded = menuRouteLoaded
    }
  },
  actions: {
    getMenuTree({ commit }) {
      let userInfo = JSON.parse(localStorage.getItem('user_info'))

      let data = {
        userId: userInfo.userId,
        tenantId: userInfo.tenantId,
        appId: userInfo.tenantAppId
      }

      return new Promise((resolve) => {
        findMenuTreeSideBar(data).then((response) => {
          resolve(response.data)
        })
        // resolve(findMenuTree().data.data); // 测试环境,暂时使用
      }).then((data) => {
        return new Promise((resolve) => {
          // 保存加载状态
          commit('setMenuRouteLoaded', true)
          // 保存菜单树
          // data.unshift({
          //   id: '-1',
          //   menuIcon: 'el-icon-s-comment',
          //   menuName: '首页',
          //   url: '/welcome',
          //   children: [],
          //   component: '/welcome',
          //   type: {
          //     value: 0,
          //     desc: '目录'
          //   },
          //   parent: {}
          // })
          commit('setMenuTree', data)

          resolve(data)
        })
      })
    },
    getPerList({ commit }) {
      let userInfo = JSON.parse(localStorage.getItem('user_info'))

      let data = {
        userId: userInfo.userId,
        tenantId: userInfo.tenantId,
        appId: userInfo.tenantAppId
      }

      return new Promise((resolve) => {
        findMenuList(data).then((response) => {
          resolve(response.data)
        })
        getPermissionList().then((res) => {
          commit('setPerms', res.data.value)
        })
        // resolve(findMenuList().data.data) // 测试环境,暂时使用
      }).then((data) => {
        return new Promise((resolve) => {
          let temp = data
            .filter((n) => {
              return n.type.value === 0 || n.type.value === 1
            })
            .map((m) => m.url.toLowerCase())
          // 保存菜单权限列表
          commit('setMenuList', temp)
          resolve(temp)
        })
      })
    },
    resetPermissionLoad({ commit }) {
      commit('setMenuRouteLoaded', false)
    }
  }
}

页面访问:

import { mapGetters } from 'vuex'

 computed: {

    ...mapGetters(['menuTree']),

  },

通过this.menuTree访问

或者this.$store.getters['menuTree']

二、vuex模块化 vuex使用详解-Module模块

默认情况下,模块内部的 action 和 mutation 仍然是注册在全局命名空间的——这样使得多个模块能够对同一个 action 或 mutation 作出响应。Getter 同样也默认注册在全局命名空间,但是目前这并非出于功能上的目的(仅仅是维持现状来避免非兼容性变更)。必须注意,不要在不同的、无命名空间的模块中定义两个相同的 getter 从而导致错误。

如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。

模块注册方式:modules和registerModule

modules方式:

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

Vue.use(Vuex)
const stateData = {
  functionType: '', //运行类型FORMAL_OPERATION_PROJECT正式,INFORMAL_OPERATION_PROJECT-非正式
  consignInfo: '', //合同信息-甲方(客户)
  transportInfo: '', //签约主体-乙方
  contractTime: '', //承运合同-合同时间
  isSameShipper: false, //收货方是否同发货方
  shipper: {}, //发货方
  projectName: '', //项目名称
  commissionRate: 0 //佣金比例
}
const mutations = {
  setFunctionType(state, val) {
    state.functionType = val
  },
  setConsignInfo(state, val) {
    state.consignInfo = val
  },
  setTransportInfo(state, val) {
    state.transportInfo = val
  },
  setContractTime(state, val) {
    state.contractTime = val
  },
  setIsSameShipper(state, val) {
    state.isSameShipper = val
  },
  setShipper(state, val) {
    state.shipper = val
  },
  setProjectName(state, val) {
    state.projectName = val
  },
  setCommissionRate(state, val) {
    state.commissionRate = val
  }
}
const getters = {
  functionType: (state) => {
    return state.functionType
  },
  consignInfo: (state) => {
    return state.consignInfo
  },
  transportInfo: (state) => {
    return state.transportInfo
  },
  contractTime: (state) => {
    return state.contractTime
  },
  isSameShipper: (state) => {
    return state.isSameShipper
  },
  shipper: (state) => {
    return state.shipper
  },
  projectName: (state) => {
    return state.projectName
  },
  commissionRate: (state) => {
    return state.commissionRate
  }
}
const add = {
  namespaced: true,
  state: () => _.cloneDeep(stateData),
  mutations,
  getters,
  actions: {}
}
const edit = {
  namespaced: true,
  state: () => _.cloneDeep(stateData),
  mutations,
  getters,
  actions: {}
}
export default new Vuex.Store({
  modules: {
    add,
    edit
  }
})

registerModule方式:

import Vue from 'vue';
import Vuex from 'vuex';
import {
	store
} from '@gtff/tdesign-gt-vue';
import zrsq from './modules/zrgl/zrsq';
import comlq from './modules/comlq';

const initStore = store.init(Vue, Vuex);

initStore.registerModule('index', {
	namespaced: true,
	state: {
		user: 'index name',
		userId: '10214406000000023059',
	},
	getters: {
		userId(state) {
			console.log(new Date())
			return state.userId
		}
	},
	mutations: {
		changeUserId(state, id) {
			state.userId = id;
		}
	},
	actions: {
		changeUserIdFun({ commit }, args) {
			commit('changeUserId', args)
		}
	}
});
initStore.registerModule('zrsq', zrsq);
initStore.registerModule('comlq', comlq);
export default initStore;


页面使用:

import { mapGetters, mapState, mapActions, mapMutations } from 'vuex'
export default {

  computed: {
    // ...mapGetters(['userId']),
    ...mapGetters(['index/userId']),
    ...mapState({
      userId1: state => state.index.userId
    }),
  },
  mounted() {
 
    console.log('state userId', this.$store.state.index.userId)
    console.log('state mapState userId', this.userId1)

    //getters
    console.log('getters userId', this.$store.getters['userId'])
    console.log('getters mapGetters  userId', this['userId'])

   
    //getters-命名空间
    console.log('getters userId', this.$store.getters['index/userId'])
    console.log('getters mapGetters  userId', this['index/userId'])

    //mutations
    this.$store.commit('changeUserId', '223333')
    this['changeUserId']('4445555')

    //actions
    this.$store.dispatch('changeUserIdFun', 'aaaaaa')
    this['changeUserIdFun']('bbbbb')

    //mutations-命名空间
    this.$store.commit('index/changeUserId', '223333')
    this['index/changeUserId']('4445555')

    //actions-命名空间
    this.$store.dispatch('index/changeUserIdFun', 'aaaaaa')
    this['index/changeUserIdFun']('bbbbb')

  },
  methods: {
    // ...mapMutations(['index/changeUserId']),
    // ...mapActions(['index/changeUserIdFun']),
    ...mapMutations(['changeUserId']),
    ...mapActions(['changeUserIdFun']),
  },

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了实现Vuex模块的持久化存储,可以使用vuex-persistedstate插件。下面是实现Vuex模块持久化存储的步骤: 1. 安装vuex-persistedstate插件: ```shell npm i vuex-persistedstate@3.2.1 ``` 2. 在Vuex store中引入vuex-persistedstate插件: ```javascript import Vuex from 'vuex' import createPersistedState from 'vuex-persistedstate' const store = new Vuex.Store({ // ... plugins: [createPersistedState()] }) ``` 3. 在Vuex store中定义需要持久化存储的模块: ```javascript import user from './modules/user' const store = new Vuex.Store({ modules: { user }, plugins: [createPersistedState()] }) ``` 在上面的代码中,我们将user模块定义为需要持久化存储的模块。 4. 在需要持久化存储的模块中添加一个`namespaced`属性: ```javascript const user = { namespaced: true, // ... } ``` 5. 在需要持久化存储的模块中添加一个`mutations`属性: ```javascript const user = { namespaced: true, state: { // ... }, mutations: { // ... } } ``` 6. 在`mutations`中添加一个`RESTORE_MUTATION`: ```javascript import { RESTORE_MUTATION } from 'vuex-persistedstate' const user = { namespaced: true, state: { // ... }, mutations: { [RESTORE_MUTATION] (state, payload) { Object.assign(state, payload) }, // ... } } ``` 7. 在需要持久化存储的模块中添加一个`actions`属性: ```javascript const user = { namespaced: true, state: { // ... }, mutations: { // ... }, actions: { // ... } } ``` 8. 在`actions`中添加一个`init`方法: ```javascript const user = { namespaced: true, state: { // ... }, mutations: { // ... }, actions: { init ({ commit }) { commit(RESTORE_MUTATION, JSON.parse(localStorage.getItem('vuex'))) }, // ... } } ``` 9. 在Vue应用的入口文件中调用`init`方法: ```javascript import Vue from 'vue' import App from './App.vue' import store from './store' Vue.config.productionTip = false new Vue({ store, render: h => h(App), created () { this.$store.dispatch('user/init') } }).$mount('#app') ``` 现在,我们已经成功地实现了Vuex模块的持久化存储。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值