zoukankan      html  css  js  c++  java
  • vue 路由监听

    发现网上其实有很多种答案,但是测试之后发现很多都不行,或者写的不完整。

    一、在app.vue组件内,增加监听$route,如下:

    watch: {
      $route(to, from) {
        console.log(to);
        console.log(from);
        if (‘条件判断’) {
            // 需要处理的业务逻辑
            console.log(1234533);
        }
      }
    }
    

      二、路由独享的守卫

      在路由配置上直接定义 beforeEnter 守卫:

          

    const router = new VueRouter({
      routes: [
        {
          path: '/foo',
          component: Foo,
          beforeEnter: (to, from, next) => {
            // ...
          }
        }
      ]
    })
    

      三、组件内的守卫

           在路由组件内直接定义以下路由导航守卫:

    • beforeRouteEnter
    • beforeRouteUpdate (2.2 新增)
    • beforeRouteLeave
    • const Foo = {
        template: `...`,
        beforeRouteEnter (to, from, next) {
          // 在渲染该组件的对应路由被 confirm 前调用
          // 不!能!获取组件实例 `this`
          // 因为当守卫执行前,组件实例还没被创建
        },
        beforeRouteUpdate (to, from, next) {
          // 在当前路由改变,但是该组件被复用时调用
          // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
          // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
          // 可以访问组件实例 `this`
        },
        beforeRouteLeave (to, from, next) {
          // 导航离开该组件的对应路由时调用
          // 可以访问组件实例 `this`
        }
      }
      

        

      beforeRouteEnter 守卫 不能 访问 this,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建。

      不过,你可以通过传一个回调给 next来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。

      beforeRouteEnter (to, from, next) {
        next(vm => {
          // 通过 `vm` 访问组件实例
        })
      }
      

        注意 beforeRouteEnter 是支持给 next 传递回调的唯一守卫。对于 beforeRouteUpdate 和 beforeRouteLeave 来说,this 已经可用了,所以不支持传递回调,因为没有必要了。

    • beforeRouteUpdate (to, from, next) {
        // just use `this`
        this.name = to.params.name
        next()
      }
      

        这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false) 来取消。

    • beforeRouteLeave (to, from , next) {
        const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
        if (answer) {
          next()
        } else {
          next(false)
        }
      }
      

        

  • 相关阅读:
    yml 配置文件注入
    STS 自动生成 getter 和 setter
    maven build 失败
    navicat 使用
    STS 设置 注解提示
    windows下安装Mysql
    安装 mysql
    用Navicat Premium 操作MySQL数据库
    渐变显示渐变消失的BackgroundView
    基于dispatch_after封装YXTimer
  • 原文地址:https://www.cnblogs.com/alvin553819/p/9046277.html
Copyright © 2011-2022 走看看