我的目标:
我不会创建将为所有请求设置带标记的标头的插件。
问题:
插件无效。
注释:
插件应添加到存储模块中。 (在这种情况下,这可能很重要。我不知道)
插件代码:
export default function(store){
store.subscribe((mutation, state) => {
if(mutation.type === "GetToken"){
console.log('TOKEN: ' + state.token);
Vue.http.interceptors.push((request, next) => {
request.headers.set('Authorization', 'Bearer ' +state.token);
next();
});
}
});
}
存储代码:
import AuthenticationPlugin from "../plugins/authorization"
export default {
namespaced: true,
plugins: [AuthenticationPlugin],
state:{
token: null,
email: null,
signinResponse:{
ok: null,
status: null,
statusText: null,
url: null,
data: null,
},
},
getters:{
userToken(state){
return state.token;
},
userSigninResponseOk(state){
return state.signinResponse.ok;
},
userSigninResponseStatus(state){
return state.signinResponse.status;
},
userSigninResponseStatusText(state){
return state.signinResponse.statusText;
},
userSigninResponseUrl(state){
return state.signinResponse.url;
},
userSigninResponseData(state){
return state.signinResponse.data;
},
},
mutations:{
GetToken(state, credentials){
let c = credentials;
let s = state;
s.email = c.email;
Vue.http.post('api/admin/signin', {
'email': c.email ,
'password': c.password,
}).then(response=>{
let r = response,
d = r.data,
s = state,
sr= s.signinResponse;
s.token = d.hasOwnProperty('token') ? d.token : null;
sr.ok = r.ok;
sr.status = r.status;
sr.statusText = r.statusText;
sr.url = r.url;
sr.data = r.data;
}, response=>{
let r = response,
d = r.data,
s = state,
sr= s.signinResponse;
sr.token = null;
sr.ok = r.ok;
sr.status = r.status;
sr.statusText = r.statusText;
sr.url = r.url;
sr.data = r.data;
});
}
},
actions:{
GetToken(context, credentials){
context.commit('GetToken', credentials);
}
},
}
答案 0 :(得分:0)
如果您想听模块突变,则必须使用模块寄存器名称来调用mutation。而且我不知道插件可以注入模块,所以我认为插件应该注入到store.js文件中
我的
import ObservePlugin from "./ObservePlugin";
Vue.use(Vuex);
export default new Vuex.Store({
...
modules: {
'sampleModule': SampleModule
}
plugins :[
ObservePlugin
]
})
订阅命名空间模块更改:
store.subscribe((mutation, state) => {
if(mutation.type === 'sampleModule/mutationName') {
console.log(mutation)
}
})