vue全局前置守卫控制访问权限

1.配置路由

路由配置中添加,如下配置:

 meta:{

    requiresAuth:true,

    title:"Vip"

  }

requiresAuth表示是否需要访问权限,值为true,需要访问权限,值为false,不需要访问权限。title为标题。

 

/**
 * Модуль роутера приложения
 */

import Vue from 'vue';
import VueRouter from 'vue-router';
import initListners from './initListners';
import listners from './listners';

Vue.use(VueRouter)

const routes = [{
  path: '/vip',
  name: 'vip',
  component: () => import('../views/VipView.vue'),
  meta:{
    requiresAuth:true,
    title:"Vip"
  }
},
{
  path: '/home',
  name: 'home',
  component: () => import('../views/HomeView.vue'),
  meta:{
    requiresAuth:false,
    title:"Home"
  }
},
{
  path: '/about',
  name: 'about',
  component: () => import('../views/AboutView.vue'),
  meta:{
    requiresAuth:false,
    title:"About"
  }
  
},{
  path: '/404',
  name: '404',
  component: () => import('../views/ErrorView.vue'),
  meta:{
    requiresAuth:false,
    title:"404"
  }
}];

const router = new VueRouter({
 // mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default initListners(router, listners);

 2.权限控制

按目录src/routerbeforeeach/index.js 新建文件夹或文件

 

import router from '@/router'
import sha1 from 'js-sha1'
/* *******************导航守卫******************* */
let queryURLParams = (URL) => {
  let obj = {}; // 声明参数对象
  if (URL.includes("?")) {
    // const url = location.search; // 项目中可直接通过search方法获取url中"?"符后的字串
    let url = URL.split("?")[1];
    let arr = url.split("&"); // 以&符号分割为数组
    for (let i = 0; i < arr.length; i++) {
      let arrNew = arr[i].split("="); // 以"="分割为数组
      obj[arrNew[0]] = decodeURIComponent(arrNew[1]);
    }
  } else {
    obj = {
      VODACC: "",
      STAMP: null,
      SSOKEY: null,
    }
  }
  return obj;
}
let URL = window.location.href //"http://192.168.1.183:8080/#/vip?SSOKEY=ad1b8114fc8702169244e1c9e60358e618f29aef&STAMP=31558673374&VODACC=vz"// 
console.log(queryURLParams(URL))
let queryURLParamsObj = queryURLParams(URL)
/*取 VODACC 1、用户名*/
let VODACC = queryURLParamsObj.VODACC
/*取 STAMP ,登录时间戳(精确到秒),时间戳验证,时间戳超过5分钟则判定过期,限制登录*/
let STAMP = queryURLParamsObj.STAMP//Date.parse(new Date()) - 60//;
/*取 SSOKEY SHA1(链接秘钥+loginid+stamp)的值等于token,即视为合法*/
let SSOKEY = queryURLParamsObj.SSOKEY;
let TokenState = sha1("VOD$&!" + VODACC + STAMP)
let timestamp = Date.parse(new Date()) / 1000
let DelayState = (timestamp - Number(STAMP)) > (5 * 60) ? false : true
console.log("TokenState:", TokenState)
console.log("DelayState:", timestamp, STAMP, (timestamp - Number(STAMP)), DelayState)
console.log("VODACC && STAMP && SSOKEY && timestamp - STAMP < 5 * 60:", !!VODACC && !!STAMP && !!SSOKEY && DelayState)

router.beforeEach((to, from, next) => {
  if (!to.meta.requiresAuth) {
    next()
  } else {
    if (VODACC && STAMP && SSOKEY && DelayState) {//&& timestamp - STAMP < 5 * 60
      if (SSOKEY == TokenState) {
        if (to.path !== '/vip') {
          next({ path: '/vip' })
        } else {
          next()
        }
      } else {

        // 如果没有权限,则跳转到 404 页面
        if (to.path === '/404') {
          next()
        } else {
          next({ path: '/404' })


        }
      }

    } else {
      // 如果没有权限,则跳转到 404 页面
      if (to.path === '/404') {
        next()
      } else {
        next({ path: '/404' })


      }
    }
  }



})

/* *******************导航守卫******************* */

router.afterEach((to) => {
  // 根据路由 meta 设置标题
  if (to.meta && to.meta.title) {
    document.title = to.meta.title
  } else {
    document.title = '默认标题'
  }
})

// 错误处理
router.onError((error) => {

  const pattern = /Loading chunk (\d)+ failed/g;

  const isChunkLoadFailed = error.message.match(pattern);

  const targetPath = router.history.pending.fullPath;

  if (isChunkLoadFailed) {

    router.replace(targetPath);

  }

})

 或者

import router from '@/router'
import sha1 from 'js-sha1'
/* *******************导航守卫******************* */
let queryURLParams = (URL) => {
  let obj = {}; // 声明参数对象
  if (URL.includes("?")) {
    // const url = location.search; // 项目中可直接通过search方法获取url中"?"符后的字串
    let url = URL.split("?")[1];
    let arr = url.split("&"); // 以&符号分割为数组
    for (let i = 0; i < arr.length; i++) {
      let arrNew = arr[i].split("="); // 以"="分割为数组
      obj[arrNew[0]] = decodeURIComponent(arrNew[1]);
    }
  } else {
    obj = {
      VODACC: "",
      STAMP: null,
      SSOKEY: null,
    }
  }
  return obj;
}
let URL = window.location.href //"http://192.168.1.180:8082/#/home?SSOKEY=4455559c84204a184e08c96b1aafb4227&STAMP=4075505785&VODACC=vz"// 
console.log(queryURLParams(URL))
let queryURLParamsObj = queryURLParams(URL)
/*取 VODACC 1、用户名*/
let VODACC = queryURLParamsObj.VODACC
/*取 STAMP ,登录时间戳(精确到秒),时间戳验证,时间戳超过5分钟则判定过期,限制登录*/
let STAMP = queryURLParamsObj.STAMP//Date.parse(new Date()) - 60//;
/*取 SSOKEY SHA1(链接秘钥+loginid+stamp)的值等于token,即视为合法*/
let SSOKEY = queryURLParamsObj.SSOKEY;
let TokenState = sha1("VOD$&!" + VODACC + STAMP)
let timestamp = Date.parse(new Date()) / 1000
let DelayState = (timestamp - Number(STAMP)) > (5 * 60) ? false : true
console.log("DelayState:", timestamp, STAMP, (timestamp - Number(STAMP)), DelayState)
console.log("VODACC && STAMP && SSOKEY && timestamp - STAMP < 5 * 60:", !!VODACC && !!STAMP && !!SSOKEY && DelayState)

router.beforeEach((to, from, next) => {
  if (to.path === '/about') {
    next()
  } else {
    if (VODACC && STAMP && SSOKEY && DelayState) {//&& timestamp - STAMP < 5 * 60
      if (SSOKEY == TokenState) {
        if (to.path !== '/home') {
          next({ path: '/home' })
        } else {
          next()
        }
      } else {

        // 如果没有权限,则跳转到 404 页面
        if (to.path === '/404') {
          next()
        } else {
          next({ path: '/404' })


        }
      }

    } else {
      // 如果没有权限,则跳转到 404 页面
      if (to.path === '/404') {
        next()
      } else {
        next({ path: '/404' })


      }
    }
  }



})

/* *******************导航守卫******************* */

router.afterEach((to) => {
  // 根据路由 meta 设置标题
  if (to.meta && to.meta.title) {
    document.title = to.meta.title
  } else {
    document.title = '默认标题'
  }
})

// 错误处理
router.onError((error) => {

  const pattern = /Loading chunk (\d)+ failed/g;

  const isChunkLoadFailed = error.message.match(pattern);

  const targetPath = router.history.pending.fullPath;

  if (isChunkLoadFailed) {

    router.replace(targetPath);

  }

})

3.在main.js里引入

 

import './routerbeforeeach/index'

 main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './routerbeforeeach/index'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
import moment from "moment";
Vue.prototype.$moment = moment;



Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

4.时间戳获取 

时间戳获取:https://www.beijing-time.org/shijianchuo/

 

 

5.效果图

 

 

 

 

 源码地址:https://github.com/1t1824d/vue_routerbeforeeach_axios

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

volodyan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值