【发布时间】: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