vue 最简单的登录页面判断是否登录,是就进入首页,不是就返回登录页面
最简单的vue判断是否登录,没有登录返回登录页面,登录就进入首页
·
首先做一个简单的登录页面
<!--这里我用了element组件-->
<template>
<div class="login">
<div>
<el-input placeholder="请输入用户名" v-model="name" clearable class="input_style"></el-input>
<span v-if="error.name" class="err-msg">{{error.name}}</span>
</div>
<div>
<el-input placeholder="请输入密码" v-model="pwd" show-password class="input_style"></el-input>
<span v-if="error.pwd" class="err-msg">{{error.pwd}}</span>
</div>
<div>
<el-button type="primary" @click="login" class="login_style">登录</el-button>
</div>
</div>
</template>
<script>
export default {
name: "Login",
data(){
return {
name: '',
pwd : '',
error : {
name: '',
pwd : ''
}
}
},
methods:{
login() {
if (!this.name) {
this.$message.error("请输入用户名!");
return;
} else if (!this.pwd) {
this.$message.error("请输入密码!");
return;
} else {
if(this.name == 'admin'){ //判断账号是否正确
if(this.pwd == '123456'){ //判断密码是否正确
sessionStorage.setItem('accessToken', 12321);//为了测试存了一个写死的token,一般情况获取后端返回token
this.$router.push({ path: "/123" });//如果账号密码正确跳转到首页
}else{
this.$message.error("账号密码错误");
return;
}
}
}
}
}
}
</script>
<style>
.login{
margin-top: 200px;
margin-left: 40%;
}
.input_style{
width: 20%;
margin-bottom: 10px;
}
.login_style{
width: 200px;
}
</style>
实现登录页面判断,最直接的方法就是使用路由拦截
Vue的登录拦截主要通过router的配置实现。 requireAuth属性作用是表明该路由是否需要登录验证,在进行全局拦截时,我们将通过该属性判断路由的跳转
import Vue from 'vue'
import VueRouter from 'vue-router'
import main from '../components/layout/main.vue'
Vue.use(VueRouter)
const routes = [{
path: '/',
name: 'Home',
component: main,
redirect: '/123',
children: [
{
path: '123',
meta: {
requireAuth: true //这里配置一下requireAuth属性作用是表明该路由是否需要登录验证,在进行全局拦截时,我们将通过该属性判断路由的跳转,该属性包含在meta属性中: next: 跳转方法
},
component: () =>
import ( /* webpackChunkName: "jsc" */ '../123.vue')
},
},
]
const router = new VueRouter({
routes
})
//这里设置路由拦截
router.beforeEach((to, from, next) => {
if (to.meta.requireAuth) { //判断是否需要登录验证
var num = sessionStorage.getItem("accessToken"); //这里是登录页面缓存的token
if (num == 12321) { //判断token等于时候就跳转路由
next();//这个跳转是上面路由跳转
}
else { //token不一样时候就返回登录页面
next({
path: '/login',//返回登录界面
// query: {redirect: to.fullPath}
})
}
}
else {
//如果不需要登录权限就直接跳转到该路由
next();
}
}
)
export default router
更多推荐
已为社区贡献1条内容
所有评论(0)