Use vue-router + vuex navigation guard (rpm)

Introduction: want to achieve Sign in to the main page and other pages, or will jump to the login page. But Vuex there is not a perfect place, will refresh the page once gone, so have to use localStorage.

A, 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; 
Here are four places need to focus on (the introduction and use of which is not included):

1. routes array used to store a single routing variables, and each router has a meta object requires parameters, which has a requiresAuth (other names may be ordered), this is used to determine a page to be required to judge the permissions, login page is false, other pages are true.


 

2.new a router objects, just pay attention to point 1 of the array as a parameter, then the router and finally export the objects to another page references.
3. Refresh the page to have a judgment, there is no re-assignment login. This time the judge localStorage isLogin, if true, it is refreshing login before you submit trigger vuex change the status.
4.vue-router provides the hook function, when the replacement route will trigger this function, this time we should use meta.requiresAuth attention to point 1, if the page is about to enter requires judgment login privileges, detect vuex of isLogin , it is true you can go, or have to jump to the login page.

Two, Vuex

 
File Locations

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 

Third, the actual use -> Login

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; } }); }, 

Fourth, the actual use -> Log

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>


Author: Lia Code piglets
link: https: //www.jianshu.com/p/f920b0e994dc
Source: Jane book
Jane book copyright reserved by the authors, are reproduced in any form, please contact the author to obtain authorization and indicate the source.

Guess you like

Origin www.cnblogs.com/snowhite/p/11277429.html