使用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. 开发过程中,尽量有着面向对象的思想,这 ...
随机推荐
- 图论初步-Tarjan算法及其应用
暑假刷了一堆Tarjan题到头来还是忘得差不多. 这篇博客权当复习吧. 一些定义 无向图 割顶与桥 (划重点) 图G是连通图,删除一个点表示删除此点以及所有与其相连的边. 若删除某点u后G不再连通,那 ...
- 自定义一个简单的SegmentedControl
先大概看下我们想实现简单的效果 源码 // // DSegmentedControl.swift // IOS学习之自定义UISegmentedControl // // Created by din ...
- struts2和springmvc性能比较2
我们用struts2时采用的传统的配置文件的方式,并没有使用传说中的0配置.spring3 mvc可以认为已经100%零配置了(除了配置spring mvc-servlet.xml外). Spring ...
- Swift 浅谈Struct与Class
讨论Struct与Class之前,我们先来看一个概念:Value Type(值类型),Reference Type(引用类型): 1. 值类型的变量直接包含他们的数据,对于值类型都有他们自己的数据副本 ...
- 码海拾遗:strstr()、strcmp()和strcpy()实现
1.strstr()实现 原型:char * strstr(const char * str1, const char * str2) 说明:判断str2是否为str1的子串,如果是则返回str2第一 ...
- 【NOIP14 D2T2】寻找道路
Source and Judge NOIP2014 提高组 D2T2Luogu2296Caioj1567 Problem [Description] 在有向图 G 中,每条边的长度均为 1,现给定起点 ...
- 如何安装与配置MySQL
关键词:MySQL,安装,配置 这一节,我们讨论一下MySQL的安装配置与卸载 下载 网址:https://dev.mysql.com/downloads/mysql/ 选择社区版,找到对应的电脑,开 ...
- Linux USB 鼠标驱动程序详解(转)
Linux USB 鼠标驱动程序详解 USB 总线引出两个重要的链表!一个 USB 总线引出两个重要的链表,一个为 USB 设备链表,一个为 USB 驱动链表.设备链表包含各种系统中的 USB 设备以 ...
- 安卓权威编程指南 挑战练习(第26章 在 Lollipop 设备上使用 JobService)
26.11 挑战练习:在 Lollipop 设备上使用 JobService 请创建另一个 PollService 实现版本.新的 PollService 应该继承 JobService 并使用 Jo ...
- 【简单版】hexo博客搭建流程梳理
前言 本文章会为你梳理一个搭建hexo博客的流程 相关网址: Docs: https://hexo.io/docs/ Themes: https://hexo.io/themes/ 安装hexo 准备 ...