使用vue-router+vuex进行导航守卫(转)
前言:想要实现登录后才能进入主页等其他页面,不然都会跳转到登录页。但是Vuex有个不够完美的地方,一旦刷新页面就会没了,所以还要用到localStorage。
一、router.js:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import store from '../store/index'
Vue.use(Router);
// 懒加载组件
const login = () => import('Components/common/login/index.vue');
const loading = () => import('Components/common/loading/index.vue');
const home = () => import('Pages/home/home.vue');
const user = () => import('Pages/userManage/index.vue');
const addUser = () => import('Pages/userManage/add/index.vue');
const editUser = () => import('Pages/userManage/edit/index.vue');
const menu = () => import('Pages/menuManage/index.vue');
const umbrella = () => import('Pages/umbrellaManage/index.vue');
const location = () => import('Pages/locationManage/index.vue');
const order = () => import('Pages/orderManage/index.vue');
const test = () => import('Pages/test.vue');
const routes = [
// 登录页面
{
path: '/login',
name: "login",
component: login,
meta: {
requiresAuth: false
}
},
{
path: '*',
redirect: '/home',
name: 'HelloWorld',
component: HelloWorld,
children: [
// 测试页面
{
path: '/test',
component: test,
meta: {
requiresAuth: true
}
},
// loading页面
{
path: '/loading',
name: "loading",
component: loading,
meta: {
requiresAuth: true
}
},
// 主页
{
path: '/home',
component: home,
meta: {
requiresAuth: true
}
},
// 用户管理
{
path: '/user',
component: user,
meta: {
requiresAuth: true
}
},
{
path: '/user/add',
name: 'addUser',
component: addUser,
meta: {
requiresAuth: true
}
},
{
path: '/user/edit',
name: 'editUser',
component: editUser,
meta: {
requiresAuth: true
}
},
// 菜单管理
{
path: '/menu',
name: 'menu',
component: menu,
meta: {
requiresAuth: true
}
},
// 雨伞管理
{
path: '/umbrella',
name: 'umbrella',
component: umbrella,
meta: {
requiresAuth: true
}
},
// 租借点管理
{
path: '/location',
name: 'location',
component: location,
meta: {
requiresAuth: true
}
},
// 订单管理
{
path: '/order',
name: 'order',
component: order,
meta: {
requiresAuth: true
}
},
]
}
];
// 页面刷新时,重新赋值有没登录
if (window.localStorage.getItem('isLogin')) {
store.commit('setIsLogin', window.localStorage.getItem('isLogin'));
}
const router = new Router({
routes
});
router.beforeEach((to, from, next) => {
if (to.matched.some(r => r.meta.requiresAuth)) { // 判断该路由是否需要登录权限
console.log(store.getters.isLogin);
if (store.getters.isLogin) { // 通过vuex 如果当前有登录
next();
}
else {
console.log("没有登录吖")
next({
path: '/login',
query: {redirect: to.fullPath}
})
}
}
else {
next();
}
});
export default router;
这里有四个需要重点关注的地方(引入和使用就不纳入其中了):
1.单独一个routes数组用来存放路由变量,然后每一个路由对象都需要有个meta参数,里面有个requiresAuth(也可以命其他名),这个就是用来判断这个页面需不需要判断权限,所以login页面为false,其他页面都为true。

2.new一个router对象,刚刚在注意点1的数组作为参数,然后最后导出这个router对象给其他页面引用。
3.要有一个判断页面刷新,重新赋值有没登录。这个时候判断localStorage中的isLogin,如果为true,所以刷新前是有登录的,则提交触发vuex更改状态。
4.vue-router提供的钩子函数,在路由更换的时候,都会触发这个函数,这个时候就要用到注意点1的meta.requiresAuth,如果即将要进入的页面需要判断登录权限,检测vuex的isLogin,为true就可以进去,不然都跳转到登录页面。
二、Vuex

modules/login.js
const login = {
state: {
// true为已经登录,false为没登录
isLogin: false
},
mutations: {
setIsLogin(state, isLogin) {
state.isLogin = isLogin;
}
},
actions: {
},
}
export default login;
getters.js
const getters = {
isCollapse: state => state.nav.isCollapse,
isLogin: state => state.login.isLogin
};
export default getters
index.js
import Vue from 'vue';
import Vuex from 'vuex';
import nav from './modules/nav'
import login from './modules/login'
// import app from './modules/app';
// import user from './modules/user';
// import menu from './modules/menu';
import getters from './getters';
Vue.use(Vuex);
const store = new Vuex.Store({
strict: process.env.NODE_ENV !== 'production',
modules: {
nav,
login
// app,
// user,
// menu
},
getters
});
export default store
三、实际使用-->登录
handleSubmit() {
this.$refs["loginForm"].validate((valid) => {
if (valid) {
if(this.loginForm.userName === "admin" && this.loginForm.password === "admin") {
this.$notify({
title: '恭喜你',
message: '登录成功!',
type: 'success'
});
// 触发setIsLogin方法改变vuex中isLogin的值,
this.$store.commit('setIsLogin', true);
// 改变localStorage中isLogin的值,
window.localStorage.setItem('isLogin', true);
// Cookies.set('Token', response.data.token)
this.$router.push({path: '/home'});
}
else {
this.$message({
message: '登录失败:密码错误!',
type: 'warning'
});
}
} else {
console.log('error submit!!');
return false;
}
});
},
四、实际使用-->退出登录
handleCommand(command) {
if(command === "exit") {
// 触发setIsLogin方法改变vuex中isLogin的值,
this.$store.commit('setIsLogin', false);
// 改变localStorage中isLogin的值,
window.localStorage.setItem('isLogin', false);
this.$notify({
title: '退出登录成功',
message: '请重新登录',
type: 'success'
});
this.$router.push({path: '/login'});
}
}
<el-dropdown @command="handleCommand">
<span class="el-dropdown-link">
欢迎你,{{name}}<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item command="exit">退出登录</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
作者:Lia代码猪崽
链接:https://www.jianshu.com/p/f920b0e994dc
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
使用vue-router+vuex进行导航守卫(转)的更多相关文章
- Vue3: 如何以 Vite 创建,以 Vue Router, Vuex, Ant Design 开始应用
本文代码: https://github.com/ikuokuo/start-vue3 在线演示: https://ikuokuo.github.io/start-vue3/ Vite 创建 Vue ...
- Vue 2.0 + Vue Router + Vuex
用 Vue.js 2.x 与相配套的 Vue Router.Vuex 搭建了一个最基本的后台管理系统的骨架. 当然先要安装 node.js(包括了 npm).vue-cli 项目结构如图所示: ass ...
- 【VUE】5.路由导航守卫
1. 功能需求 1. 当用户登陆成功后,把得到的token存到Session Storage 2. components -> Form.vue , 对预验证进行校验,如果验证不正确就跳出,如果 ...
- Vue(基础八)_导航守卫(组件内的守卫)
一.前言 主要通过一个例子演示三个钩子的作用: 1.beforeRouteEnter() ...
- Vue躬行记(8)——Vue Router
虽然Vue.js未提供路由功能,但是官方推出了Vue Router(即vue-router库),以插件的形式支持.它与Vue.js深度集成,可快速的创建单页应用(Single Page Applica ...
- Vue.js路由管理器 Vue Router
起步 HTML <script src="https://unpkg.com/vue/dist/vue.js"></script> <script s ...
- Vue Router 路由守卫:完整的导航解析流程
完整的导航解析流程 1 导航被触发. 2 在失活的组件里调用离开守卫. 3 调用全局的 beforeEach 守卫. 4 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+). ...
- vue router 导航守卫生命周期
导航守卫 导航守卫主要用来通过跳转或取消的方式守卫导航.有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的.(记住参数或查询的改变并不会触发进入/离开的导航守卫.你可以通过观察$r ...
- vue 按需加载,缓存,导航守卫
开发中的注意事项:代码性能的优化 1. 减少对第三方的依赖,降低耦合度 2. 加强组件的重复利用率 3. 按需加载 4. 缓存 (尽量发送请求后保存数据) 5. 开发过程中,尽量有着面向对象的思想,这 ...
随机推荐
- java异常分析;剖析printStackTrace和fillInStackTrace
Java异常的栈轨迹(Stack Trace) 捕获到异常时,往往需要进行一些处理.比较简单直接的方式就是打印异常栈轨迹Stack Trace.说起栈轨迹,可能很多人和我一样,第一反应就是printS ...
- mysql 子查询 合并查询
4.1带In 关键字的子查询 一个查询语句的条件可能落在另一个SELECT 语句的查询结果中. SELECT * FROM t_book WHERE booktypeId IN (SELECT id ...
- haproxy笔记之三:配置HAProxy详细介绍
2.1 配置文件格式 HAProxy的配置处理3类来主要参数来源:——最优先处理的命令行参数,——“global”配置段,用于设定全局配置参数:——proxy相关配置段,如“defaults”.“li ...
- (七)spring+druid多数据源配置
druid多数据源配置 一.druid简介 Druid首先是一个数据库连接池,但它不仅仅是一个数据库连接池,它还包含一个ProxyDriver,一系列内置的JDBC组件库,一个SQL Parser. ...
- python标准库-builtin 模块之compile,execfile
eval函数仅仅允许执行简单的表达式.对于更大的代码块时,使用compile和exec函数. 例子:使用 compile函数验证语法 NAME = "script.py" BODY ...
- google搜索运算符+101个Google技巧 - Google技巧的终极收集
下面内容整理自网络 搜索运算符 如果您使用我们的基本搜索技巧后,并未找到想要搜索的内容,可以尝试使用搜索运算符.您只需在 Google 搜索框中将这些符号或字词添加到搜索字词中,即可更好地掌控要显示的 ...
- python基础函数、方法
python的函数和方法,通过def 定义: 函数的特性: 减少重复代码 使程序变的可扩展 使程序变得易维护 函数和方法的区别:函数有返回值.方法没有 语法定义: def sayhi():#函数名 p ...
- xshell 常用命令1
date命令 date命令是显示或设置系统时间与日期. 很多shell脚本里面需要打印不同格式的时间或日期,以及要根据时间和日期执行操作.延时通常用于脚本执行过程中提供一段等待的时间.日期可以以多种格 ...
- MySQL5.7彻底取消主从复制
由于手误在master节点执行了stop slave;->change master to XXX;->start slave;的动作,后面虽然使用stop slave停止了主从复制,但是 ...
- 大忙人的jdk8,比出生晚了好几个激情的夏天
写给大忙人的jdk8到手了,第一件事情就蒙蔽了,mac装的jdk7,切换jdk的功能要整出来才行,下好jdk8up101安装,假装几行代码搞定目标在命令行下,可以通过命令'jdk6', 'jdk7', ...