如何从模块访问 Vuex 基础状态
How to access a Vuex base state from a module
我在Vuex中成功建了一个群,但是如何从群进入到base/non群状态呢?在这种情况下,我想从产品组的 base/non 组状态中的状态访问用户令牌。
这是我的产品组
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”获取令牌时出错
这是我的用户令牌代码
export const store = new Vuex.Store({
modules: {
product
},
state:{
token: localStorage.getItem('access_token') || null,
filter: 'all',
},
})
如果你看到了,我已经声明了一个变量标记并用 access_token
填充了它。我可以从产品组调用这个变量,还是必须在产品组中创建另一个标记变量?
或者我是否必须让其他组保留令牌?
这个可以通过命名空间解决吗?
由于操作在 Vuex 模块中,并且您正在访问的状态在 Vuex 存储根而不是模块状态中,因此您需要从 context
对象访问 rootState
而不是 state
:
axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.rootState.token
context
对象有:
state
rootState
getters
rootGetters
commit
dispatch
我在Vuex中成功建了一个群,但是如何从群进入到base/non群状态呢?在这种情况下,我想从产品组的 base/non 组状态中的状态访问用户令牌。
这是我的产品组
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”获取令牌时出错
这是我的用户令牌代码
export const store = new Vuex.Store({
modules: {
product
},
state:{
token: localStorage.getItem('access_token') || null,
filter: 'all',
},
})
如果你看到了,我已经声明了一个变量标记并用 access_token
填充了它。我可以从产品组调用这个变量,还是必须在产品组中创建另一个标记变量?
或者我是否必须让其他组保留令牌?
这个可以通过命名空间解决吗?
由于操作在 Vuex 模块中,并且您正在访问的状态在 Vuex 存储根而不是模块状态中,因此您需要从 context
对象访问 rootState
而不是 state
:
axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.rootState.token
context
对象有:
state
rootState
getters
rootGetters
commit
dispatch