Vue编程式路由导航和路由守卫

<router-link>的replace属性

  • 作用:控制路由跳转时操作浏览器历史记录的模式
  • 浏览器历史记录有两种写入方式:分别有push和replace,push是追加历史记录,replace是替换当前记录,路由跳转时是push
  • 如何开启replace模式:
    <router-link replace ...>news</router-link>
    

编程式路由导航

  • 作用:不借助<router-link>实现路由跳转,让路由跳转更加灵活
  • 具体编码:
    methods: {
      pushShow(m) {
        this.$router.push({
          name: 'msg-d',   // 就是路由的名称,不能使用path
          params: {
            id: m.id,
            title: m.title,
            views: m.views
          }
        })
      },
      replaceShow(m) {
        this.$router.replace({
          name: 'msg-d',   // 就是路由的名称,不能使用path
          params: {
            id: m.id,
            title: m.title,
            views: m.views
          }
        })
      },
      back() {  // 后退
        this.$router.back()
      },
      forward() {   // 前进
        this.$router.forward()
      },
    },
    

路由守卫

  • 全局路由守卫
    // 全局前置路由守卫——初始化的时候被调用,每次路由切换之前被调用
    router.beforeEach((to, from, next) => {
      // to and from are both route objects. must call `next`.
      if(to.meta.isAuth){
        if(localStorage.getItem("user") === 'xiansen'){
          next();
        }else{
          alert("您没有权限!");
        }
      }else{
        next();
      }
    })
    
    // 全局后置路由守卫——初始化的时候被调用,每次路由切换之后被调用
    router.afterEach((to, from) => {
      // to and from are both route objects.
      document.title = to.meta.title || '测试Vue脚手架'
    })
    
  • 独享路由守卫(在路由中配置该属性,方法功能和上面的一样)
    beforeEnter:(to, from, next) => {   // 独享路由守卫
      if(to.meta.isAuth){
        if(localStorage.getItem("user") === 'xiansen'){
          next();
        }else{
          alert("您没有权限!");
        }
      }else{
        next();
      }
    },
    
posted @ 2022-02-27 13:38  xsha_h  阅读(239)  评论(0编辑  收藏  举报