Web前端vue必做笔记之一:token验证登录状态
当我们登录页不输入账号和密码时,直接访问内容页路径,会发现也可以进行访问,这就会产生一个bug,这是就需要进行token验证登录
<template>
<div>
<form @submit.prevent="login">
<div>
<label for="">用户名:</label>
<input type="text" v-model="username">
</div>
<div>
<label for="">密码:</label>
<input type="password" v-model="password">
</div>
<button></button>
</form>
</div>
</template>
<script>
export default {
data(){
return {
username:'',
password:''
}
},
methods:{
login(){
if(this.username === 'admin' && this.password ==='123456'){
this.$router.push('/')
localStorage.setItem("token","xiaoming")
}else{
alert("用户名或密码错误!");
}
}
}
}
</script>
import {createRouter, createWebHashHistory} from 'vue-router'
import Home from './components/Home'
import Blog from './components/Blog'
import Login from './components/Login'
const router = createRouter({
history:createWebHashHistory(),
router:[
{
path:'/',
component:Home
},
{
path:'/blog',
component:Blog
},
{
path:'/login',
component:Login
}
]
});
router.beforeEach((to,from,next)=>{
let token = localStorage.getItem("token");
if( token || to.path === '/login'){
next()
}else{
next('/login')
}
})
export default router
|