【问题标题】:How to access a Vuex base state from a module如何从模块访问 Vuex 基本状态
【发布时间】:2021-05-15 16:33:01
【问题描述】:

我在 Vuex 中成功创建了一个组,但是我如何从组访问到基本/非组状态?在这种情况下,我想从产品组的基本/非组状态中的状态访问用户令牌。

这是我的产品组

const product = {
  state: () => ({
    product: [

    ]
  }),
  mutations: {
    retreiveProduct(state,product){
      state.product = product
    },
  },
  actions: {
    retreiveProduct(context){
      axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token
      axios.get('/products')
        .then(response=>{
          context.commit('retreiveProduct',response.data)
        })
        .catch(error => {console.log(error)})
    },
  },
  getters: {

  }
}

上面代码中从“context.state.token”获取token时出错

这是我的用户令牌代码

export const store = new Vuex.Store({
  modules: {
    product
  },
  state:{
    token: localStorage.getItem('access_token') || null,
    filter: 'all',
  },
})

如果你看到了,我已经声明了一个变量标记并用access_token 填充它。我可以从产品组中调用此变量,还是必须在产品组中创建另一个令牌变量?

还是我必须让其他组保留令牌?

这可以通过命名空间解决吗?

【问题讨论】:

  • 你可以将 token 作为参数传递给 action,然后你可以调用 this.$store.dispatch('retreiveProduct', {product, token});
  • 在这种情况下,我建议使用拦截器为每个请求传递令牌,或者当令牌已经在 localStorage 中时,您不需要将令牌存储在 store 中。在操作中,您还可以访问 localStorage。

标签: javascript vue.js token vuex vuex-modules


【解决方案1】:

由于操作在 Vuex 模块中,并且您正在访问的状态是在 Vuex 存储根而不是模块的状态中,因此您需要从 context 对象而不是 state 访问 rootState

axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.rootState.token

context 对象有:

  • state
  • rootState
  • getters
  • rootGetters
  • commit
  • dispatch

【讨论】:

  • 还有一件事,在我登录路由器后,我重定向到 /productall 并且数据 json 在那里,但是当我重新加载 /productall 数据 json 为空时,响应为空,在产品组件中我创建了() 对于检索到的产品,我的代码有什么问题?
  • 你应该为此发布一个新问题,因为它是关于其他事情的,并且也让其他人有机会回答
猜你喜欢
  • 2017-05-12
  • 1970-01-01
  • 2019-11-17
  • 2021-08-27
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 2019-03-22
相关资源
最近更新 更多