vue router拦截器的简单使用

之前,为了实现router跳转的每个页面的url上都带上addressCode,然后用了一下router拦截器,很好用,当然也可以专门封装一个方法来实现(跳转的页面上带有addressCode),不过还是感觉router拦截器比较省事。

router拦截器就是在路由跳转前后,做一些事情,相当于一个钩子函数。

下面说一下使用方法:

1、在main.js里  引入router

import router from "./router/router";

2、要在 vue实例前写入

//注册一个全局前置守卫,确保要调用 next 方法,否则钩子就不会被 resolved
router.beforeEach((to, from, next) => {
  //路由切换时,如果没有就添加,有就跳过执行,添加固定参数
  if (!to.query.addressCode) {
      //准备一个跳转的query对象
      let query = to.query
      query.addressCode = tool.getAddressCode();//是一个封装好的获取addressCode的方法
      alert.eduToast('没'+query.addressCode,6000);//调试代码
      next({
        path: to.path,
        query: query
      })
  } else {
      if (to.path !== window.location.pathname) {
        // 此处不可使用location.replace
          window.location.assign(to.fullPath)
        } else {
          next()
        }
      alert.eduToast('有',6000);//调试代码
  }
})

猜你喜欢

转载自www.cnblogs.com/fqh123/p/10360894.html