vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vuex存储token

vuex存储token示例

作者:zyx_

今天小编就为大家分享一篇vuex存储token示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

1.在login.vue中通过发送http请求获取token

//根据api接口获取token 
var url = this.HOST + "/session"; 
this.$axios.post(url, { 
username: this.loginForm.username, 
password: this.loginForm.pass 
}).then(res => { 
// console.log(res.data); 
this.$message.success('登录成功'); 
let data = res.data; 
//根据store中set_token方法将token保存至localStorage/sessionStorage中,data["Authentication-Token"],获取token的value值 
this.$store.commit('set_token', data["Authentication-Token"]); 
 
if (store.state.token) { 
this.$router.push('/') 
console.log(store.state.token) 
} else { 
this.$router.replace('/login'); 
} 
 
}).catch(error => { 
// this.$message.error(error.status) 
this.loading = false 
this.loginBtn = "登录" 
this.$message.error('账号或密码错误'); 
// console.log(error) 
 
}) 

2.在store.js中对token状态进行监管

import Vue from 'vue' 
import Vuex from 'vuex' 
 
 
Vue.use(Vuex) 
 
export default new Vuex.Store({ 
state:{ 
token:'' 
}, 
mutations:{ 
set_token(state, token) { 
state.token = token 
sessionStorage.token = token 
}, 
del_token(state) { 
state.token = '' 
sessionStorage.removeItem('token') 
} 
} 
}) 

3.在router/index.js中

// 页面刷新时,重新赋值token 
if (sessionStorage.getItem('token')) { 
store.commit('set_token', sessionStorage.getItem('token')) 
} 
 
const router = new Router({ 
mode: "history", 
routes 
}); 
 
router.beforeEach((to, from, next) => { 
if (to.matched.some(r => r.meta.requireAuth)) {      //这里的requireAuth为路由中定义的 meta:{requireAuth:true},意思为:该路由添加该字段,表示进入该路由需要登陆的 
if (store.state.token) { 
next(); 
} 
else { 
next({ 
path: '/login', 
query: {redirect: to.fullPath} 
}) 
} 
} 
else { 
next(); 
} 
}) 

4.在main.js中定义全局默认配置:

Axios.defaults.headers.common['Authentication-Token'] = store.state.token;

5.在src/main.js添加拦截器

// 添加请求拦截器 
Axios.interceptors.request.use(config => { 
// 在发送请求之前做些什么 
//判断是否存在token,如果存在将每个页面header都添加token 
if(store.state.token){ 
config.headers.common['Authentication-Token']=store.state.token 
} 
 
return config; 
}, error => { 
// 对请求错误做些什么 
return Promise.reject(error); 
}); 
 
// http response 拦截器 
Axios.interceptors.response.use( 
response => { 
 
return response; 
}, 
error => { 
 
if (error.response) { 
switch (error.response.status) { 
case 401: 
this.$store.commit('del_token'); 
router.replace({ 
path: '/login', 
query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面 
}) 
} 
} 
return Promise.reject(error.response.data) 
}); 

1.在login.vue中通过发送http请求获取token

//根据api接口获取token 
var url = this.HOST + "/session"; 
this.$axios.post(url, { 
username: this.loginForm.username, 
password: this.loginForm.pass 
}).then(res => { 
// console.log(res.data); 
this.$message.success('登录成功'); 
let data = res.data; 
//根据store中set_token方法将token保存至localStorage/sessionStorage中,data["Authentication-Token"],获取token的value值 
this.$store.commit('set_token', data["Authentication-Token"]); 
 
if (store.state.token) { 
this.$router.push('/') 
console.log(store.state.token) 
} else { 
this.$router.replace('/login'); 
} 
 
}).catch(error => { 
// this.$message.error(error.status) 
this.loading = false 
this.loginBtn = "登录" 
this.$message.error('账号或密码错误'); 
// console.log(error) 
 
}) 

2.在store.js中对token状态进行监管

import Vue from 'vue' 
import Vuex from 'vuex' 
 
 
Vue.use(Vuex) 
 
export default new Vuex.Store({ 
state:{ 
token:'' 
}, 
mutations:{ 
set_token(state, token) { 
state.token = token 
sessionStorage.token = token 
}, 
del_token(state) { 
state.token = '' 
sessionStorage.removeItem('token') 
} 
} 
}) 

3.在router/index.js中

// 页面刷新时,重新赋值token 
if (sessionStorage.getItem('token')) { 
store.commit('set_token', sessionStorage.getItem('token')) 
} 
 
const router = new Router({ 
mode: "history", 
routes 
}); 
 
router.beforeEach((to, from, next) => { 
if (to.matched.some(r => r.meta.requireAuth)) {      //这里的requireAuth为路由中定义的 meta:{requireAuth:true},意思为:该路由添加该字段,表示进入该路由需要登陆的 
if (store.state.token) { 
next(); 
} 
else { 
next({ 
path: '/login', 
query: {redirect: to.fullPath} 
}) 
} 
} 
else { 
next(); 
} 
}) 

4.在main.js中定义全局默认配置:

Axios.defaults.headers.common['Authentication-Token'] = store.state.token; 

5.在src/main.js添加拦截器

// 添加请求拦截器 
Axios.interceptors.request.use(config => { 
// 在发送请求之前做些什么 
//判断是否存在token,如果存在将每个页面header都添加token 
if(store.state.token){ 
config.headers.common['Authentication-Token']=store.state.token 
} 
 
return config; 
}, error => { 
// 对请求错误做些什么 
return Promise.reject(error); 
}); 
 
// http response 拦截器 
Axios.interceptors.response.use( 
response => { 
 
return response; 
}, 
error => { 
 
if (error.response) { 
switch (error.response.status) { 
case 401: 
this.$store.commit('del_token'); 
router.replace({ 
path: '/login', 
query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面 
}) 
} 
} 
return Promise.reject(error.response.data) 
}); 

以上这篇vuex存储token示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文