Vue 项目中 根目录中router路由拦截 beforeEach 常用的写法

上代码吧
在我们的router.js文件下

	/*
	 * @Description: 路由设置
	 */
	import Vue from "vue";
	import Router from "vue-router";
	import store from '../store/store';  // 用到的vuex--store
	// 封装的路由引入进来
	import nd from './nd';
	import q from './q';
	// 按钮权限
	import {getCurrentModuleBtnPermission} from "../utils/btnPermission" // 按钮权限操作
	
	Vue.use(Router);
	
	//解决Vue-Router升级导致的没有捕获导航 Uncaught(in promise) navigation guard问题
	
	const originalPush = Router.prototype.push // 路由原型中的push
	Router.prototype.push = function push(location, onResolve, onReject) {
	  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
	  return originalPush.call(this, location).catch(err => err)
	}
	
	// 使用引入的路由
	const routes = [
		...nd, ...q, 
		{
		  path: "/",
		  redirect: "login",
		  auth: false
		}
	]
	
	const router = new Router({
	  mode: 'history',
	  routes
	});
	
	// 路由拦截操作
	router.beforeEach((to, from, next) => {
		//判断是否需要登录
	  if (to.matched.some(res => res.meta.auth)) { // 如果匹配到了信息就可以直接登录
	    if (sessionStorage['username']) { // 如果有找到以存在的 username
	    	// 权限btn
	    	// some()是对数组中每一项运行给定函数,如果该函数有一项返回true,则返回true。
	      if (to.matched.some(res => res.meta.btn)){
	      		// 权限按钮操作
	          getCurrentModuleBtnPermission(to.fullPath).then((res) => {
		            if (res.code == "SUCCESS") {
		              sessionStorage.setItem('btnPermission',res.data);
		            }
	          });
	      }
		// 提交一个commit 事件 
	      store.commit('setHistory', to);
	      next();
	    } else {// 如果没有权限btn
	      sessionStorage.clear(); // 清空 存储信息,进入登录页面
	      next({
	        path: "/login",
	        query: {
	          redirect: to.fullPath // 重定向
	        }
	      });
	    }
	  } else { // 如果没有匹配到信息
	    store.commit('setHistory', to);
	    next()
	  }
	})
	export default router

上面我们说道了权限,并且有路由里的meta标记,你一定要注意在我们路由配置里面添加meta , 并给值,如下图
在这里插入图片描述

然后继续。
我们在store文件夹下创建一个store.js文件

import Vue from 'vue'
import Vuex from 'vuex'
import { setToken } from '@/utils/storage.js'

Vue.use(Vuex)

const store = new Vuex.Store({
	// 基本数据信息
    state: {
        id_token: '', //token
        Loading: false, // loading 控制
        index: localStorage.getItem('index') || 1, // 底部导航状态
        lang: 'cn', // 语言
        history: []
    },
	//异步操作
    mutations: {
        SET_TOKEN(state, token) {
            state.id_token = token
        },
        isLoading(state) {
            state.Loading = !state.Loading;
        },
        isIndex(state, n) {
            localStorage.setItem('index', n);
            state.index = n;
        },
        setLang(state, lang) {
            localStorage.setItem('lang', lang);
            state.lang = lang;
        },
        
        setHistory(state, n) {
            // 过滤相同数据
            let arr = state.history;
            let isa = arr.filter(item => item.path == n.path);
            if (isa.length == 0) {
                // 判断是否是欢迎页
                if (n.path != '/welcome' && n.meta.name) {
                    state.history.push(n);
                }
            }
        },

        reduceHistory(state, n) {
            // 删除记录
            let arr = state.history;
            let index;
            arr.forEach((item, i) => {
                if (item.path == n.path) {
                    index = i;
                }
            })
            arr.splice(index, 1);
        },
        allHistory(state) {
            // 关闭全部
            sessionStorage.removeItem('history');
            state.history = [];
        },
        otherHistory(state, n) {
            // 关闭其他
            if (state.history.length) {
                state.history = [];
                state.history.push(n);
            }
        }
    },
    
    // 同步操作
    actions: {
        setToken({ commit }, token) {
            return new Promise((resolve, reject) => {
                commit('SET_TOKEN', token)
                setToken(token)
                resolve()
            })
        },
        editLoading(context) {
            context.commit('isLoading');
        },
        editIndex(context, n) {
            context.commit('isIndex', n);
        }
    }
});


export default store

那么我们继续写按钮权限文件,要后端配合了

import http from '../plugin/axios';

let api = {
  btnPermission: '/gateway/energy-service-ucenter/api/roles/btn/permission', // 获取按钮权限
}
/**
 * 按钮权限判断
 * @param value
 * @returns {boolean}
 */
	export function checkBtnPermission(value) {
	   const permissions = sessionStorage.getItem('btnPermission')
	    if(null == permissions){
	       return false;
	    }
	    return permissions.indexOf(value) != -1
	}

export function getCurrentModuleBtnPermission(data) {
  return http.gets(api.btnPermission, {"path":data});
}

结束。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值