vue中的登陆拦截
程序员文章站
2022-04-18 13:50:07
...
首先说思路,通过在如有规则中使用meta属性,再配合钩子函数beforeEach,实现登陆拦截功能
router.js:
import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/pages/login'
import Home from '@/pages/home'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/login',
name: 'L',
component: Login
},
{
path: '/home',
name: 'H',
component: Home,
meta:{ //将home页设置为需要登录验证
requireAuth: true
}
}
]
})
使用全局的路由前置守卫
main.js:
router.beforeEach((to,from,next)=>{
if (to.meta.requireAuth) {
if (localStorage.user) {
next();
}
else {
next({
path: '/login',
query: {redirect: to.fullPath}
})
}
}
else {
next();
}
})
登陆页面的简单实现,如果用户登陆,就把用户信息存到localstorage中,在前置的路由守卫中通过判断localstorage中是否有用户信息,实现登陆拦截功能
login.vue:
<template>
<div class="box">
<div class="login" @click="select(0)">login</div>
<div class="sign" @click="select(1)">sign</div>
<div class="bb bb-active"></div>
<div class="bb"></div>
<div class="login-box" v-if="isLogin">
<el-input v-model="name" placeholder="name"></el-input>
<el-input v-model="pwd" placeholder="password"></el-input>
</div>
<div v-else>
sign
</div>
<span class="btn" v-show="btnFlag" @click="goLogin">login</span>
<span class="dis-btn" v-show="!btnFlag">login</span>
</div>
</template>
<script>
import md5 from 'js-md5'
export default {
name: 'login',
data(){
return {
isLogin: true,
name: '',
pwd: '',
btnFlag: false
}
},
methods:{
select(index){
if(index == 0){
this.isLogin = true
} else{
this.isLogin = false
}
let bbList = document.getElementsByClassName('bb')
for(let i=0;i<bbList.length;i++){
if(i == index){
bbList[i].className = 'bb bb-active';
}else{
bbList[i].className = 'bb';
}
}
},
goLogin(){
this.pwd = md5(this.pwd)
alert(this.pwd)
let userObj = {
name: this.name,
pwd: this.pwd
}
localStorage.setItem("user",JSON.stringify(userObj))
this.$router.push('/home')
}
},
watch:{
name(val,newVal){
if(this.name && this.pwd){
this.btnFlag = true
}else{
this.btnFlag = false
}
},
pwd(val,newVal){
if(this.name && this.pwd){
this.btnFlag = true
}else{
this.btnFlag = false
}
}
},
beforeCreate(){
document.querySelector('body').setAttribute('style', 'background-color:#09f')
},
beforeDestroy(){
document.querySelector('body').removeAttribute('style')
}
}
</script>
<style lang="less" scoped>
.box{
overflow-y: none;
width: 400px;
margin: 100px auto;
background: white;
border-radius: 5px;
padding-bottom: 20px;
.login,.sign{
float: left;
width: 50%;
height: 50px;
line-height: 50px;
border:1px solid #E4E7ED;
box-sizing: border-box;
cursor: pointer;
}
.sign{
border-left: 0;
}
.login{
border-right: 0;
}
.bb{
float: left;
width: 50%;
height: 2px;
background: transparent;
margin-bottom: 20px;
}
.bb-active{
background: #09f;
}
.el-input{
width: 80%;
margin: 10px 0 10px 0;
}
.btn,.dis-btn{
font-size:18px;
color: white;
line-height: 50px;
margin: 20px auto;
border-radius: 10px;
display: block;
width: 80%;
cursor: pointer;
}
.btn{
background: #09f;
}
.dis-btn{
background: #eee;
}
}
</style>
end
上一篇: HDU -> ACM -> Shopping
下一篇: 复习和js知识学习