Vue項(xiàng)目中實(shí)現(xiàn)用戶登錄及token驗(yàn)證
先說一下我的實(shí)現(xiàn)步驟:
- 使用
easy-mock
新建登錄接口它碎,模擬用戶數(shù)據(jù) - 使用
axios
請求登錄接口砂轻,匹配賬號和密碼 - 賬號密碼驗(yàn)證后虎敦, 拿到
token
,將token存儲到sessionStorage
中,并跳轉(zhuǎn)到首頁 - 前端每次跳轉(zhuǎn)時慈俯,就使用導(dǎo)航守衛(wèi)(vue-router.beforeEach)判斷
sessionStorage
中有無token
栏尚,沒有就跳轉(zhuǎn)到登錄頁面起愈,有則跳轉(zhuǎn)到對應(yīng)路由頁面。 - 注銷后译仗,就清除
sessionStorage
里的token
信息并跳轉(zhuǎn)到登錄頁面
使用easy-mock模擬用戶數(shù)據(jù)
我用的是easy-mock,新建了一個接口抬虽,用于模擬用戶數(shù)據(jù):
{
"error_code": 0,
"data": [{
"id": '1',
"usertitle": "管理員",
"username": "admin",
"password": "123456",
"token": "@date(T)",
},
{
"id": '2',
"usertitle": "超級管理員",
"username": "root",
"password": "root",
"token": "@date(T)",
}
]
}
login.vue中寫好登陸框:
<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
,用來請求剛剛定義好的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('賬號不存在!');
}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)入首頁
this.startHacking ('登錄成功古劲!');
//跳轉(zhuǎn)到首頁
this.$router.push('/index');
// console.log(this.$router);
}else{
alert('密碼錯誤斥赋!')
}
}
}).catch(err=>{
console.log('連接數(shù)據(jù)庫失敗产艾!')
})
}
這一步最重要的是當(dāng)賬號密碼正確時疤剑,把請求回來的token
放在sessionStorage
中,
配置路由
然后配置路由新加一個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
中配置一個全局前置鉤子函數(shù):router.beforeEach()
隘膘,他的作用就是在每次路由切換的時候調(diào)用
這個鉤子方法會接收三個參數(shù):to、from杠览、next弯菊。
to
:Route:即將要進(jìn)入的目標(biāo)的路由對象,
from
:Route:當(dāng)前導(dǎo)航正要離開的路由踱阿,
next
:Function:個人理解這個方法就是函數(shù)結(jié)束后執(zhí)行什么管钳,先看官方解釋
1.next()
:進(jìn)行管道中的下一個鉤子钦铁。如果全部鉤子執(zhí)行完了,則導(dǎo)航的狀態(tài)就是confirmed(確認(rèn)的)才漆,
2.next(false)
:中斷當(dāng)前的導(dǎo)航牛曹。如果瀏覽器的url改變了(可能是用戶手動或?yàn)g覽器后退按鈕),那么url地址會重置到from路由對應(yīng)的地址醇滥。
3.next('/')
或next({path:'/'})
:跳轉(zhuǎn)到一個不同的地址黎比。當(dāng)前導(dǎo)航被中斷,進(jìn)入一個新的導(dǎo)航鸳玩。
用sessionStorage存儲用戶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)下 訪問login.vue頁面 會跳到index.vue
next({path: '/index'});
}else{
next();
}
}else{
// 如果沒有session ,訪問任何頁面阅虫。都會進(jìn)入到 登錄頁
if (to.path === '/') { // 如果是登錄頁面的話,直接next() -->解決注銷后的循環(huán)執(zhí)行bug
next();
} else { // 否則 跳轉(zhuǎn)到登錄頁面
next({ path: '/' });
}
}
})
這里用了router.beforeEach
vue-router導(dǎo)航守衛(wèi)
每次跳轉(zhuǎn)時都會判斷sessionStorage
中是否有token
值不跟,如果有則能正常跳轉(zhuǎn)颓帝,如果沒有那么就返回登錄頁面。
注銷
至此就完成了一個簡單的登錄狀態(tài)了窝革,瀏覽器關(guān)閉后sessionStorage
會清空的躲履,所以當(dāng)用戶關(guān)閉瀏覽器再打開是需要重新登錄的
當(dāng)然也可以手動清除sessionStorage
,清除動作可以做成注銷登錄聊闯,這個就簡單了工猜。
loginOut(){
// 注銷后 清除session信息 ,并返回登錄頁
window.sessionStorage.removeItem('data');
this.common.startHacking(this, 'success', '注銷成功菱蔬!');
this.$router.push('/index');
}
寫一個清除sessionStorag
的方法篷帅。
一個簡單的保存登錄狀態(tài)的小Demo。
參考:
騰訊云社區(qū)-Vue+SessionStorage實(shí)現(xiàn)簡單的登錄
SF-從前后端分別學(xué)習(xí)——注冊/登錄流程2
Vue-router實(shí)現(xiàn)單頁面應(yīng)用在沒有登錄情況下拴泌,自動跳轉(zhuǎn)到登錄頁面
vue+axios新手實(shí)踐實(shí)現(xiàn)登陸
Vue實(shí)戰(zhàn)(四)登錄/注冊頁的實(shí)現(xiàn)
vue頁面控制權(quán)限,vuex刷新保存狀態(tài)魏身、登錄狀態(tài)保存
vue頁面控制權(quán)限,vuex刷新保存狀態(tài)、登錄狀態(tài)保存
(vue.js)前后端分離的單頁應(yīng)用如何來判斷當(dāng)前用戶的登錄狀態(tài)蚪腐?
Vue登錄注冊箭昵,并保持登錄狀態(tài)
vue登錄注冊及token驗(yàn)證
Vue項(xiàng)目中實(shí)現(xiàn)用戶登錄及token驗(yàn)證
vue-router守衛(wèi)導(dǎo)航官方文檔:vue-router導(dǎo)航守衛(wèi)