vuex

122 阅读1分钟

持久化插件

1、安装插件

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate' // localStorage存储持久化
import Login from './login'
Vue.use(Vuex)

export default new Vuex.Store({
  plugins: [createPersistedState()],
  modules: {
    // 这里的路径名: test1, test2, 在view 中 通过 mapActions('test1', [actionName]) 使用并区分需要使用的module
    Login
  }
})

2、模块化使用

/** 登录模块需要存的数据 */
const Login = {
  namespaced: true,
  state: {
    func: {}
  },
  mutations: {
    saveFunc (state, data) {
      // const funcObj = {
      //   // 123456: true,
      //   // 456789: true,
      //   300100: true,
      //   300101: true,
      //   300102: true,
      //   300103: true,
      //   300104: true
      // }
      state.func = data
    }
  },
  actions: {
    saveActionFunc ({ commit }, data) {
      return new Promise((resolve, reject) => {
        const funcObj = {
          123456: true,
          // 456789: true,
          300100: true,
          300101: true,
          300102: true,
          // 300103: true,
          // 300104: true,
          300106: true
        }
        commit('saveFunc', funcObj)
        resolve(funcObj)
      })
    }
  }
}
export default Login

3、页面中使用

computed: {
  ...mapState('Login', ['func'])
},
mounted () {
  console.log(this.func, 'this.func in store')
},
methods: {
  ...mapActions('Login', ['saveActionFunc']),
  handelLogin (formName) {
    // this.$store.dispatch('Login/saveActionFunc')
        this.saveActionFunc()
  }
}

vuex 插件地址

www.extfans.com/web-develop…