Vue之beforeEach非登錄不能訪問的實現(代碼親測)
更新時間:2019年07月18日 11:08:33 作者:快醒醒
這篇文章主要介紹了Vue之beforeEach非登錄不能訪問的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
后臺的php請求就是接收這兩個參數
login.vue
<template>
<div class=''>
<input type="text" v-model="name" />
<input type="password" v-model="password" />
<button type="primary" @click="submitForm"><router-link :to="{path:'/'}">提交</router-link></button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data(){
return{
name:'',
password:'',
}
},
methods:{
submitForm:function(){
var params = new URLSearchParams();
params.append('name', this.name);
params.append('password',this.password);
axios({
method: 'post',
url: '/api/bbb.php',
data:params
}).then((resp)=>{
sessionStorage.setItem('token',resp.status)// localStorage
//以key value的形式將值存放到sessionStorage中。
console.log(resp);
}).catch((error)=>{
console.log(error);
})
}
}
}
</script>
router
{
path: '/',
name: 'HelloWorld',
component: HelloWorld,
meta:{requireAuth:true}
},
main.js
router.beforeEach((to, from, next) => {
console.log(to);
console.log(from);
console.log( sessionStorage.getItem('token'))
if (to.meta.requireAuth) { // 判斷該路由是否需要登錄權限
if(sessionStorage.getItem('token')){ //判斷sessionStorage是否存在token
alert("已經登錄了")
next();
}else{
//防止死循環(huán)
alert("暫時未登錄")
if (to.path === '/login') {
next();
return
}else{
next({
path: '/login',
});
}
}
}
else {
next();
}
/*如果本地 存在 token 則 不允許直接跳轉到 登錄頁面*/
if(to.fullPath == "/login"){
if(localStorage.getItem('token')){
next({
path:from.fullPath
});
}else {
next();
}
}
});
注意一定要在router實例前使用
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue3?v-bind="$attrs"繼承組件全部屬性的解決方案
這篇文章主要介紹了vue3?v-bind=“$attrs“?繼承組件全部屬性的解決方案,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-06-06
SyntaxError:?/xx.vue:?Unexpected?token,?expected?“,“錯誤解
這篇文章主要為大家介紹了SyntaxError:?/xx.vue:?Unexpected?token,?expected?“,“錯誤解決方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08
vue.js出現Vue.js?not?detected錯誤的解決方案
這篇文章主要介紹了vue.js出現Vue.js?not?detected錯誤的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
VUE 直接通過JS 修改html對象的值導致沒有更新到數據中解決方法分析
這篇文章主要介紹了VUE 直接通過JS 修改html對象的值導致沒有更新到數據中解決方法,結合實例形式詳細分析了VUE使用JS修改html對象的值導致沒有更新到數據的原因與解決方法,需要的朋友可以參考下2019-12-12
在vue中使用css modules替代scroped的方法
本篇文章主要介紹了在vue中使用css modules替代scroped的方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03
Vite+TS+Vue開啟eslint和prettier規(guī)范及校驗方式
這篇文章主要介紹了Vite+TS+Vue開啟eslint和prettier規(guī)范及校驗方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06

