Reputation: 1865
My goal:
I wont to create plugin that will setup header with token for all requests.
Problem:
Plugin doesn't work.
Comments:
Plugin should be added to the storage module. (May be it matters something in this case. I don't know)
Plugin code:
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();
});
}
});
}
storage code:
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);
}
},
}
Upvotes: 0
Views: 1054
Reputation: 31
If you want listen to module mutations, you must call mutation with module register name. And i don't know the plugin can inject at module, so i think plugin should inject to in store.js file
My
import ObservePlugin from "./ObservePlugin";
Vue.use(Vuex);
export default new Vuex.Store({
...
modules: {
'sampleModule': SampleModule
}
plugins :[
ObservePlugin
]
})
Subscribe for namespaced module mutation:
store.subscribe((mutation, state) => {
if(mutation.type === 'sampleModule/mutationName') {
console.log(mutation)
}
})
Upvotes: 1