vuex存儲(chǔ)token示例
1.在login.vue中通過(guò)發(fā)送http請(qǐng)求獲取token
//根據(jù)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;
//根據(jù)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('賬號(hào)或密碼錯(cuò)誤');
// console.log(error)
})
2.在store.js中對(duì)token狀態(tài)進(jìn)行監(jiān)管
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中
// 頁(yè)面刷新時(shí),重新賦值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},意思為:該路由添加該字段,表示進(jìn)入該路由需要登陸的
if (store.state.token) {
next();
}
else {
next({
path: '/login',
query: {redirect: to.fullPath}
})
}
}
else {
next();
}
})
4.在main.js中定義全局默認(rèn)配置:
Axios.defaults.headers.common['Authentication-Token'] = store.state.token;
5.在src/main.js添加攔截器
// 添加請(qǐng)求攔截器
Axios.interceptors.request.use(config => {
// 在發(fā)送請(qǐng)求之前做些什么
//判斷是否存在token,如果存在將每個(gè)頁(yè)面header都添加token
if(store.state.token){
config.headers.common['Authentication-Token']=store.state.token
}
return config;
}, error => {
// 對(duì)請(qǐng)求錯(cuò)誤做些什么
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}//登錄成功后跳入瀏覽的當(dāng)前頁(yè)面
})
}
}
return Promise.reject(error.response.data)
});
1.在login.vue中通過(guò)發(fā)送http請(qǐng)求獲取token
//根據(jù)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;
//根據(jù)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('賬號(hào)或密碼錯(cuò)誤');
// console.log(error)
})
2.在store.js中對(duì)token狀態(tài)進(jìn)行監(jiān)管
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中
// 頁(yè)面刷新時(shí),重新賦值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},意思為:該路由添加該字段,表示進(jìn)入該路由需要登陸的
if (store.state.token) {
next();
}
else {
next({
path: '/login',
query: {redirect: to.fullPath}
})
}
}
else {
next();
}
})
4.在main.js中定義全局默認(rèn)配置:
Axios.defaults.headers.common['Authentication-Token'] = store.state.token;
5.在src/main.js添加攔截器
// 添加請(qǐng)求攔截器
Axios.interceptors.request.use(config => {
// 在發(fā)送請(qǐng)求之前做些什么
//判斷是否存在token,如果存在將每個(gè)頁(yè)面header都添加token
if(store.state.token){
config.headers.common['Authentication-Token']=store.state.token
}
return config;
}, error => {
// 對(duì)請(qǐng)求錯(cuò)誤做些什么
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}//登錄成功后跳入瀏覽的當(dāng)前頁(yè)面
})
}
}
return Promise.reject(error.response.data)
});
以上這篇vuex存儲(chǔ)token示例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Fragment 占位組件不生成標(biāo)簽與路由組件lazyLoad案例
這篇文章主要為大家介紹了Fragment 占位組件不生成標(biāo)簽與路由組件lazyLoad案例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
vue+導(dǎo)航錨點(diǎn)聯(lián)動(dòng)-滾動(dòng)監(jiān)聽(tīng)和點(diǎn)擊平滑滾動(dòng)跳轉(zhuǎn)實(shí)例
今天小編就為大家分享一篇vue+導(dǎo)航錨點(diǎn)聯(lián)動(dòng)-滾動(dòng)監(jiān)聽(tīng)和點(diǎn)擊平滑滾動(dòng)跳轉(zhuǎn)實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11
實(shí)用的 vue tags 創(chuàng)建緩存導(dǎo)航的過(guò)程實(shí)現(xiàn)
這篇文章主要介紹了實(shí)用的 vue tags 創(chuàng)建緩存導(dǎo)航的過(guò)程實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
基于vue-ssr的靜態(tài)網(wǎng)站生成器VuePress 初體驗(yàn)
VuePress為每一個(gè)由它生成的頁(yè)面提供預(yù)加載的html,不僅加載速度極佳,同時(shí)對(duì)seo非常友好。這篇文章主要介紹了基于vue-ssr的靜態(tài)網(wǎng)站生成器VuePress 初體驗(yàn),需要的朋友可以參考下2018-04-04
vue.js 2.0實(shí)現(xiàn)簡(jiǎn)單分頁(yè)效果
這篇文章主要為大家詳細(xì)介紹了vue.js 2.0實(shí)現(xiàn)簡(jiǎn)單分頁(yè)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07
詳解使用Vue.Js結(jié)合Jquery Ajax加載數(shù)據(jù)的兩種方式
本篇文章主要介紹了詳解使用Vue.Js結(jié)合Jquery Ajax加載數(shù)據(jù)的兩種方式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01

