首页 > 解决方案 > vuex-persistedstate:如何在 vuex-persistedstate 中使用 getter?

问题描述

我使用vuex-persistedstate。但是吸气剂不起作用。我在 Vue.js Devtools 中检查了状态,状态存在。但是吸气剂没有数据。像这样。

Chrome 中的 Vue.js 开发工具

那么如何使用吸气剂呢?

Vuex 中的 index.js

import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    login,
    segments,
    itemList,
    orderList
  },
  plugins: [
    createPersistedState()
  ]
})

vue-router 中的 index.js(我想使用 getter 进行登录状态检查)

import store from '@/store'

Vue.use(Router)

const ifAuthenticated = (to, from, next) => {
  if (store.getters.loginStatus) {
    next()
  } else {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  }
}

login.js(在 Vuex 中存储模块)

const state = {
  loginStatus: false,
  email: '',
  isStaff: false,
  company: '',
  token: ''
}
const getters = {
  loginStatus: () => state.loginStatus,
  email: () => state.email,
  isStaff: () => state.isStaff,
  company: () => state.company,
  token: () => state.token
}

标签: javascriptvue.jsvue-routervuex

解决方案


我认为您正在访问外部state对象。请尝试添加state为函数参数:

   const getters = {
      loginStatus: (state) => state.loginStatus,
      email: (state) => state.email,
      isStaff: (state) => state.isStaff,
      company: (state) => state.company,
      token: (state) => state.token
    }

推荐阅读