Vue項(xiàng)目中實(shí)現(xiàn)用戶登錄及token驗(yàn)證
先說(shuō)一下我的實(shí)現(xiàn)步驟:
- 使用
easy-mock新建登錄接口,模擬用戶數(shù)據(jù) - 使用
axios請(qǐng)求登錄接口,匹配賬號(hào)和密碼 - 賬號(hào)密碼驗(yàn)證后, 拿到
token,將token存儲(chǔ)到sessionStorage中,并跳轉(zhuǎn)到首頁(yè) - 前端每次跳轉(zhuǎn)時(shí),就使用導(dǎo)航守衛(wèi)(vue-router.beforeEach)判斷
sessionStorage中有無(wú)token,沒(méi)有就跳轉(zhuǎn)到登錄頁(yè)面,有則跳轉(zhuǎn)到對(duì)應(yīng)路由頁(yè)面。 - 注銷(xiāo)后,就清除
sessionStorage里的token信息并跳轉(zhuǎn)到登錄頁(yè)面
使用easy-mock模擬用戶數(shù)據(jù)
我用的是easy-mock,新建了一個(gè)接口,用于模擬用戶數(shù)據(jù):
{
"error_code": 0,
"data": [{
"id": '1',
"usertitle": "管理員",
"username": "admin",
"password": "123456",
"token": "@date(T)",
},
{
"id": '2',
"usertitle": "超級(jí)管理員",
"username": "root",
"password": "root",
"token": "@date(T)",
}
]
}
login.vue中寫(xiě)好登陸框:
<template>
<div>
<p>用戶名:<input type='text' v-model="userName"></p>
<p>密碼:<input type='text' v-model="passWord"></p>
<button @click="login()">登錄</button>
</div>
</template>
<script>
export default {
data() {
return {
userName:'root',
passWord:'root'
}
}
}
</script>
然后下載axios:npm install axios --save,用來(lái)請(qǐng)求剛剛定義好的easy-mock接口:
login(){
const self = this;
axios.get('https://easy-mock.com/mock/5c7cd0f89d0184e94358d/museum/login').then(response=>{
var res =response.data.data,
len = res.length,
userNameArr= [],
passWordArr= [],
ses= window.sessionStorage;
// 拿到所有的username
for(var i=0; i<len; i++){
userNameArr.push(res[i].username);
passWordArr.push(res[i].password);
}
console.log(userNameArr, passWordArr);
if(userNameArr.indexOf(this.userName) === -1){
alert('賬號(hào)不存在!');
}else{
var index = userNameArr.indexOf(this.userName);
if(passWordArr[index] === this.passWord){
// 把token放在sessionStorage中
ses.setItem('data', res[index].token);
this.$parent.$data.userTitle = res[index].usertitle;
//驗(yàn)證成功進(jìn)入首頁(yè)
this.startHacking ('登錄成功!');
//跳轉(zhuǎn)到首頁(yè)
this.$router.push('/index');
// console.log(this.$router);
}else{
alert('密碼錯(cuò)誤!')
}
}
}).catch(err=>{
console.log('連接數(shù)據(jù)庫(kù)失??!')
})
}
這一步最重要的是當(dāng)賬號(hào)密碼正確時(shí),把請(qǐng)求回來(lái)的token放在sessionStorage中,
配置路由
然后配置路由新加一個(gè)meta屬性:
{
path: '/',
name: 'login',
component: login,
meta:{
needLogin: false
}
},
{
path: '/index',
name: 'index',
component: index,
meta:{
needLogin: true
}
}
判斷每次路由跳轉(zhuǎn)的鏈接是否需要登錄,
導(dǎo)航衛(wèi)士
在main.js中配置一個(gè)全局前置鉤子函數(shù):router.beforeEach(),他的作用就是在每次路由切換的時(shí)候調(diào)用
這個(gè)鉤子方法會(huì)接收三個(gè)參數(shù):to、from、next。
to:Route:即將要進(jìn)入的目標(biāo)的路由對(duì)象,
from:Route:當(dāng)前導(dǎo)航正要離開(kāi)的路由,
next:Function:個(gè)人理解這個(gè)方法就是函數(shù)結(jié)束后執(zhí)行什么,先看官方解釋
1.next():進(jìn)行管道中的下一個(gè)鉤子。如果全部鉤子執(zhí)行完了,則導(dǎo)航的狀態(tài)就是confirmed(確認(rèn)的),
2.next(false):中斷當(dāng)前的導(dǎo)航。如果瀏覽器的url改變了(可能是用戶手動(dòng)或?yàn)g覽器后退按鈕),那么url地址會(huì)重置到from路由對(duì)應(yīng)的地址。
3.next('/')或next({path:'/'}):跳轉(zhuǎn)到一個(gè)不同的地址。當(dāng)前導(dǎo)航被中斷,進(jìn)入一個(gè)新的導(dǎo)航。
用sessionStorage存儲(chǔ)用戶token
//路由守衛(wèi)
router.beforeEach((to, from, next)=>{
//路由中設(shè)置的needLogin字段就在to當(dāng)中
if(window.sessionStorage.data){
console.log(window.sessionStorage);
// console.log(to.path) //每次跳轉(zhuǎn)的路徑
if(to.path === '/'){
//登錄狀態(tài)下 訪問(wèn)login.vue頁(yè)面 會(huì)跳到index.vue
next({path: '/index'});
}else{
next();
}
}else{
// 如果沒(méi)有session ,訪問(wèn)任何頁(yè)面。都會(huì)進(jìn)入到 登錄頁(yè)
if (to.path === '/') { // 如果是登錄頁(yè)面的話,直接next() -->解決注銷(xiāo)后的循環(huán)執(zhí)行bug
next();
} else { // 否則 跳轉(zhuǎn)到登錄頁(yè)面
next({ path: '/' });
}
}
})
這里用了router.beforeEach vue-router導(dǎo)航守衛(wèi)
每次跳轉(zhuǎn)時(shí)都會(huì)判斷sessionStorage中是否有token值,如果有則能正常跳轉(zhuǎn),如果沒(méi)有那么就返回登錄頁(yè)面。
注銷(xiāo)
至此就完成了一個(gè)簡(jiǎn)單的登錄狀態(tài)了,瀏覽器關(guān)閉后sessionStorage會(huì)清空的,所以當(dāng)用戶關(guān)閉瀏覽器再打開(kāi)是需要重新登錄的
當(dāng)然也可以手動(dòng)清除sessionStorage,清除動(dòng)作可以做成注銷(xiāo)登錄,這個(gè)就簡(jiǎn)單了。
loginOut(){
// 注銷(xiāo)后 清除session信息 ,并返回登錄頁(yè)
window.sessionStorage.removeItem('data');
this.common.startHacking(this, 'success', '注銷(xiāo)成功!');
this.$router.push('/index');
}
寫(xiě)一個(gè)清除sessionStorag的方法。
一個(gè)簡(jiǎn)單的保存登錄狀態(tài)的小Demo。
參考:
騰訊云社區(qū)-Vue+SessionStorage實(shí)現(xiàn)簡(jiǎn)單的登錄
SF-從前后端分別學(xué)習(xí)——注冊(cè)/登錄流程2
Vue-router實(shí)現(xiàn)單頁(yè)面應(yīng)用在沒(méi)有登錄情況下,自動(dòng)跳轉(zhuǎn)到登錄頁(yè)面
vue+axios新手實(shí)踐實(shí)現(xiàn)登陸
Vue實(shí)戰(zhàn)(四)登錄/注冊(cè)頁(yè)的實(shí)現(xiàn)
vue頁(yè)面控制權(quán)限,vuex刷新保存狀態(tài)、登錄狀態(tài)保存
vue頁(yè)面控制權(quán)限,vuex刷新保存狀態(tài)、登錄狀態(tài)保存
(vue.js)前后端分離的單頁(yè)應(yīng)用如何來(lái)判斷當(dāng)前用戶的登錄狀態(tài)?
Vue登錄注冊(cè),并保持登錄狀態(tài)
vue登錄注冊(cè)及token驗(yàn)證
Vue項(xiàng)目中實(shí)現(xiàn)用戶登錄及token驗(yàn)證
vue-router守衛(wèi)導(dǎo)航官方文檔:vue-router導(dǎo)航守衛(wèi)