Vue学习:实现用户没有登陆时,访问后自动跳转登录页面
设计思路
- 定义路由的时候配置属性,这里使用needLogin标记访问页面是否需要登录
- 设置路由守卫,每个页面在跳转之前都要经过验证,校验用户信息是否存在,不存在跳转到登录页
- 用户登录后将用户信息存储在localStorage
- 退出登录后,将用户信息清空
代码实现
1、router文件夹的index.js文件中
- 在router中每个地址在meta属性中配置needLogin熟悉,判断访问页面是否需要登录
- 404页面放在最后,匹配所有链接,实现输入不存在的地址时自动跳转404页面
import Vue from 'vue'
import Router from 'vue-router'
import LoginCard from "../components/LoginCard";
import Home from "../components/Home";
import ErrorPage from "../components/ErrorPage";
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'LoginCard',
component: LoginCard,
meta: {
needLogin: false
}
},
{
path: '/loginCard',
name: 'LoginCard',
component: LoginCard,
meta: {
needLogin: false
}
},
{
path: '/home',
name: 'Home',
component: Home,
meta: {
needLogin: true
}
}, {
path: '/*',
name: 'ErrorPage',
component: ErrorPage,
meta:{
needLogin: false
}
}
]
})
2、在main.js中定义一个路由前置守卫,每次跳转页面进行判断,没有登陆自动挑战登陆界面
import Vue from 'vue'
import App from './App'
import router from './router'
import VueRouter from "vue-router";
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import * as auth from './utils/auth'
import store from './store'
import Vuex from "vuex";
Vue.config.productionTip = false;
Vue.use(ElementUI);
Vue.use(VueRouter);
Vue.use(Vuex)
//这个方法需要放在new Vue之前,不然按F5刷新页面不会调用这个方法
router.beforeEach(function (to, from, next) {
console.log('是否需要登录才能访问')
if (to.meta.needLogin) {
if (auth.getAdminInfo()) {
console.log(auth.getAdminInfo())
console.log('有cookie信息')
next();
}else {
console.log('无cookie信息')
next({
path:'/loginCard'
});
}
}else{
next();
}
})
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
3、编写一个存储数据的工具,使用cookie存储用户登录后的信息
import Cookies from 'js-cookie'
const adminInfo = "adminInfo"
//获取用户信息
export function getAdminInfo() {
const admin = Cookies.get(adminInfo)
if(admin){
return JSON.parse(admin)
}
return ''
}
//存储用户信息
export function setAdminInfo(admin) {
return Cookies.set(adminInfo, JSON.stringify(admin))
}
//移除用户信息
export function removeAdminInfo() {
return Cookies.remove(adminInfo)
}
4、写一个登录页面,用户登录后就将数据存储在cookie中
<template>
<div>
<el-form ref="loginForm" :rules="formRules" :model="loginUser" label-width="80px" class="login-box">
<h3 style="margin-bottom: 50px">欢迎登录</h3>
<el-form-item label="用户名" prop="username">
<el-input prefix-icon="el-icon-user" type="text" v-model="loginUser.username" placeholder="请输入用户名" :maxlength="50" clearable></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input prefix-icon="el-icon-lock" type="password" v-model="loginUser.password" placeholder="请输入密码" :maxlength="50" clearable>
</el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">登陆</el-button>
<el-button icon="" @click="resetForm">重置</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import * as auth from '../utils/auth'
export default {
name: 'LoginCard',
data() {
return {
loginUser: {
username: '',
password: '',
},
formRules: {
//制定表单输入的规则
username: [{required: true, message: '用户名不能为空', trigger: 'blur'}],
password: [{required: true, message: '密码不能为空', trigger: 'blur'}]
}
}
},
methods: {
onSubmit() {
//判断表单是否符合规则
this.$refs['loginForm'].validate((valid) => {
if (valid) {
if (this.loginUser.username !== '123456' || this.loginUser.password !== '123456'){
this.$message({
message:'账号或密码错误',
type: 'error',
});
return;
}
auth.setAdminInfo(this.loginUser);
this.$router.push({path:'/home'});
}
}
)
},
resetForm(){
this.$refs['loginForm'].resetFields();
},
}
}
</script>
<style scoped>
.login-box {
border: 1px solid #DCDFE6;
width: 400px;
margin: 180px auto;
padding: 35px 35px 15px 35px;
border-radius: 5px;
}
</style>
5、编写一个退出页面,用户退出以后,将用户信息从cookie中去除,跳转到登陆页面
<template>
<div>
<h1>主页面</h1>
<el-button @click="logout">退出登录</el-button>
</div>
</template>
<script>
import * as auth from '../utils/auth'
export default {
name : 'Home',
data() {
return {
};
},
methods: {
logout(){
auth.removeAdminInfo();
this.$router.push({path:'/loginCard'});
}
},
mounted() {
}
}
</script>
基本目录结构是这样的

Vue学习:实现用户没有登陆时,访问后自动跳转登录页面的更多相关文章
- 【Filter 不登陆无法访问】web项目中写一个过滤器实现用户不登陆,直接给链接,无法进入页面的功能
在web项目中写一个过滤器实现用户不登陆,直接给链接,无法进入页面,而重定向到登陆界面的功能. 项目是用springMVC+spring+hibernate实现 (和这个没有多大关系) 第一步: 首先 ...
- 详解springmvc控制登录用户session失效后跳转登录页面
springmvc控制登录用户session失效后跳转登录页面,废话不多少了,具体如下: 第一步,配置 web.xml <session-config> <session-timeo ...
- nginx证书制作以及配置https并设置访问http自动跳转https(反向代理转发jboss)
nginx证书制作以及配置https并设置访问http自动跳转https 默认情况下ssl模块并未被安装,如果要使用该模块则需要在编译时指定–with-http_ssl_module参数,安装模块依赖 ...
- HBuilder开发APP自动登录时跳过"登录页面"
刚接触开发公司APP项目,用HBuilder开发工具. manifest.json中的入口页面就是"登录页面",现在获取到自动登录状态是true,但是真机联调时"登录页面 ...
- 百度Site App的uaredirect.js实现手机访问,自动跳转网站手机版
以下为代码,可放置在网站foot底部文件,或者haead顶部文件,建议将代码放在网站顶部,这样可以实现手机访问立即跳转! <script src="http://siteapp.bai ...
- ajax前置处理实现异步请求session过期时跳转登录页面
第一篇博文,mark一下zhq[0]. 问题描述:用户页面,当session过期或都session注销后,普通页面后端都会有过滤器,session过期Redirect到登录页面,但是ajax请求后端只 ...
- mediawiki登录时第一次会跳回登录页面,第二次才能登录成功
原因是:LocalSetting.php中的$wgServer属性使用的是ip,改为域名后成功解决问题 补充:改为域名后使用ip访问会出现第一次登录跳回登录界面的情况,应该根据实际情况来设置$wgSe ...
- jsp+js完成用户一定时间未操作就跳到登录页面
<% String path = request.getContextPath(); String basePath = request.getScheme() + "://" ...
- 11.VUE学习之提交表单时拿到input里的值
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...
- vue学习(四)登陆、注册、首页模板页区分
按照上面文章配置完毕后,会发现有个问题,我登陆页面.注册页面是不需要视图页的. 开始配置路由 重新配置main.js 引入 import App from './App' //引入vue组件 更改启动 ...
随机推荐
- 启动homestead虚拟机 vagrant up执行后,提示Timed out while waiting for the machine to boot
最近在启动homestead虚拟机时,总会卡在ssh验证这,几分钟后,就报timed out-- 以往都是重启电脑后,再次执行vagrant up后就能正常启动. 今日重启电脑很多次也无用. 查询解决 ...
- vivo大数据日志采集Agent设计实践
作者:vivo 互联网存储技术团队- Qiu Sidi 在企业大数据体系建设过程中,数据采集是其中的首要环节.然而,当前行业内的相关开源数据采集组件,并无法满足企业大规模数据采集的需求与有效的数据采集 ...
- svn 日常使用的错误集锦
1.SVN:Previous operation has not finished; run 'cleanup' if it was interrupted 当时遇到这个问题时,找了各种解决方案什么要 ...
- 【Java EE】Day04 MySQL多表、事务、事务隔离级别、DCL
一.多表查询 1.概述 笛卡尔积:两集合的所有组成情况 多表查询:消除笛卡尔积得到的无用数据 2.分类 内连接查询(满足指定条件无空值,只显示有关联的数据) 隐式内连接:使用where限制消除无用数据 ...
- 一定要用Photoshop?no!动手用Python做一个颜色提取器! ⛵
作者:韩信子@ShowMeAI Python3◉技能提升系列:https://www.showmeai.tech/tutorials/56 计算机视觉实战系列:https://www.showmeai ...
- SQL语句使用
目录 一:sql语句 1.什么是SQL语句? 二:基本SQL语句之库操作 三:基本SQL语句之表操作 1.查看当前所在库名称 2.切换数据库 四:基本SQL语句之记录操作 五:创建表的完整语法 六:操 ...
- python之路 57 linux 基础 命令与执行效果
虚拟环境的安装与配置 1.VMware软件安装 这里有一个15版本和一个16版本的 链接:https://pan.baidu.com/s/1vkNxxQ6NS9q7XYJ6qiVMaQ 提取码:t3l ...
- 根号分治简单笔记 | P3396 哈希冲突
简要题意 你需要维护一个长度为 \(n\) 的序列 \(v\),支持: A x y 求整个序列中,所有模 \(x\) 为 \(y\) 的下标的元素的值,即: \[\sum_{i=0}^{\lfloor ...
- CF构造题1600-1800(2)
H. Hot Black Hot White(COMPFEST 14 - Preliminary Online Mirror (Unrated, ICPC Rules, Teams Preferred ...
- 【3.x合批亲测】使用这个优化方案,iPhone6也能飞起来,直接拉满60帧!
大家好,我是晓衡! 上周我花了3天的时间,体验测试了一款 Creator 3.x 性能优化工具:98K动态分层合批. 它能将 DrawCall 超过 1000+ 次的 2D 界面,实现运行时节点分层排 ...