最近接手的B端項(xiàng)目選擇了vue來做,此項(xiàng)目使用element ui Message等為組件 望周知
需求
登陸成功后跳轉(zhuǎn)至首頁
首頁不能手動跳轉(zhuǎn)至登陸頁
登陸后跳轉(zhuǎn)至目標(biāo)頁面
此次B端SPA項(xiàng)目把a(bǔ)k存在localstorage中
1.登陸的跳轉(zhuǎn)利用全局鉤子router.beforeEach
//router.js
router.beforeEach((to, from, next) => {
// 若userkey不存在并且前往頁面不是登陸頁面,進(jìn)入登陸
// 若userkey存在并且前往登陸頁面,進(jìn)入主頁
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帶上目標(biāo)參數(shù)
例子:#/login?redirect=%2Fapp
在登陸提交處還得對redirect參數(shù)進(jìn)行處理
//若驗(yàn)證成功跳轉(zhuǎn)
var redirect = decodeURIComponent(this.$route.query.redirect || '/')
self.$router.push({
// 你需要接受路由的參數(shù)再跳轉(zhuǎn)
path: redirect
})
需求
若ak失效后發(fā)送請求時(shí)彈出失效彈出框返回到登陸頁面
以下做了個簡單的例子若請求返回的參數(shù)帶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 = '未授權(quán),請登錄'
break
case 403:
error.message = '拒絕訪問'
break
case 404:
error.message = (process.env.NODE_ENV === 'production' ? `請求地址出錯` : `請求地址出錯: ${error.response.config.url}`)
break
case 408:
error.message = '請求超時(shí)'
break
case 500:
error.message = '服務(wù)器內(nèi)部錯誤'
break
case 501:
error.message = '服務(wù)未實(shí)現(xiàn)'
break
case 502:
error.message = '網(wǎng)關(guān)錯誤'
break
case 503:
error.message = '服務(wù)不可用'
break
case 504:
error.message = '網(wǎng)關(guān)超時(shí)'
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(() => {
})
}
簡單的登陸登出結(jié)束啦~歡迎提isssue~