vue實現登陸登出的實現示例
更新時間:2017年09月15日 10:23:46 作者:AkiraSun
本篇文章主要介紹了vue實現登陸登出的實現示例,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
最近接手的B端項目選擇了vue來做,此項目使用element ui Message等為組件 望周知
需求
- 登陸成功后跳轉至首頁
- 首頁不能手動跳轉至登陸頁
- 登陸后跳轉至目標頁面
此次B端SPA項目把ak存在localstorage中
1.登陸的跳轉利用全局鉤子router.beforeEach
//router.js
router.beforeEach((to, from, next) => {
// 若userkey不存在并且前往頁面不是登陸頁面,進入登陸
// 若userkey存在并且前往登陸頁面,進入主頁
const userKey = localStorage.getItem('userKey')
if (!userKey && to.path !== '/login') {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else if (userKey && to.path === '/login') {
next({ path: '/' })
} else {
next()
}
})
上面使用了query帶上目標參數
例子:#/login?redirect=%2Fapp
在登陸提交處還得對redirect參數進行處理
//若驗證成功跳轉
var redirect = decodeURIComponent(this.$route.query.redirect || '/')
self.$router.push({
// 你需要接受路由的參數再跳轉
path: redirect
})
需求
若ak失效后發(fā)送請求時彈出失效彈出框返回到登陸頁面
以下做了個簡單的例子若請求返回的參數帶0則登陸失效
// respone攔截器
axios.interceptors.response.use(
response => {
console.log(response)
const data = response.data
if (data.status === 0) {
MessageBox.alert('你已被登出,可以取消繼續(xù)留在該頁面,或者重新登錄', '確定登出', {
confirmButtonText: '確定',
type: 'warning'
}).then(() => {
localStorage.clear()
router.replace({
path: '/login'
})
return
}).catch(() => {
localStorage.clear()
router.replace({
path: '/login'
})
})
} else {
return response
}
},
error => {
if (error && error.response) {
switch (error.response.status) {
case 400:
error.message = '請求錯誤'
break
case 401:
error.message = '未授權,請登錄'
break
case 403:
error.message = '拒絕訪問'
break
case 404:
error.message = (process.env.NODE_ENV === 'production' ? `請求地址出錯` : `請求地址出錯: ${error.response.config.url}`)
break
case 408:
error.message = '請求超時'
break
case 500:
error.message = '服務器內部錯誤'
break
case 501:
error.message = '服務未實現'
break
case 502:
error.message = '網關錯誤'
break
case 503:
error.message = '服務不可用'
break
case 504:
error.message = '網關超時'
break
case 505:
error.message = 'HTTP版本不受支持'
break
default:
}
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
}
return Promise.reject(error)
}
)
需求
手動登出
loginOut() {
var self = this
this.$confirm('您確定要退出嗎?', '退出管理平臺', {
confirmButtonText: '確定',
cancelButtonText: '取消'
}).then(() => {
const info = {
'userkey': localStorage.getItem('userKey')
}
self.$store.dispatch('LogOut', info).then(() => {
self.$router.push({ path: '/login' })
}).catch(() => {
})
}).catch(() => {
})
}
簡單的登陸登出結束啦~
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vue.js如何利用v-for循環(huán)生成動態(tài)標簽
這篇文章主要給大家介紹了關于Vue.js如何利用v-for循環(huán)生成動態(tài)標簽的相關資料,文中通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2022-01-01

