简单实现导航守卫

52 阅读1分钟

之前一直觉得导航守卫难搞,但是今天写了一下,觉得还可以,对于小白来说,还是可以接受的。下面就直接上代码


我是在permission.js文件里面写导航守卫的

这里是permission文件里面的代码

import router from './router/index.js'
import store from './store'
import NProgress from 'nprogress' // 页面加载的进度条
import 'nprogress/nprogress.css' // progress bar style 进度条样式

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration 进度条使用

//白名单
const whiteList = ['/','/helpCenter', '/firstpage', '/getapi'] // no redirect whitelist
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

const hasToken=localStorage.getItem('vpn_token')
const expire=localStorage.getItem('vpn_expire') //后端返回的token有效截止时间
const currentTime=Date.parse(new Date())/1000  //获取当前时间戳
  if (hasToken) {
    if (currentTime-expire>0) {
      localStorage.removeItem('vpn_token')
      localStorage.removeItem('vpn_expire')
        next({
        path: '/',
      })
    }else{
      console.log('通过');
       next()
    }
  }
  else{
     if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    }else{
      next('/')
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

最后,记得在项目入口文件引入一下上面的perssion.js文件哦!

image.png