zoukankan      html  css  js  c++  java
  • vue路由文档笔记

    引入router

    this.$router 和 router 使用起来完全一样。我们使用 this.$router 的原因是我们并不想在每个独立需要封装路由的组件中都导入路由
    可以在任何组件内通过 this.$router 访问路由器,也可以通过 this.$route 访问当前路由:

       this.$router.go(-1)
       this.$router.push('/')
       this.$route.params.username
    

    动态路由匹配

    /user/foo 和 /user/bar 都将映射到相同的路由:

        { path: '/user/:id', component: User }
    
       /user/:username/post/:post_id--->/user/evan/post/123--->$route.params:{ username: 'evan', post_id: 123 }
    

    对应的值都会设置到 $route.params 中

    从 /user/foo 导航到 /user/bar,原来的组件实例会被复用。因为两个路由都渲染同个组件,比起销毁再创建,复用则显得更加高效。不过,这也意味着组件的生命周期钩子不会再被调用。

    想对路由参数的变化作出响应的话,你可以简单地 watch (监测变化) $route 对象:

    watch: {
       '$route' (to, from) {
         // 对路由变化作出响应...
       }
     }
    

    或者使用 beforeRouteUpdate 守卫:

    嵌套路由

    当 /user/:id/profile 匹配成功, UserProfile 会被渲染在 User 的

       { path: '/user/:id', component: User,
            children: [
                {
                   path: 'profile',
                   component: UserProfile
                },
    

    js跳转页面

    声明式:

       router.push('home')  // 字符串
       router.push({ path: 'home' })  // 对象
       router.push({ name: 'user', params: { userId: 123 }})  // 命名的路由
       router.push({ path: 'register', query: { plan: 'private' }})  // 带查询参数,变成 /register?plan=private
       router.push({ path: `/user/${userId}` }) // -> /user/123  这种情况下使用params不会生效
    

    router.replace():不会向 history 添加新记录,而是替换掉当前的 history 记录。
    router.go(-1):后退一步记录,等同于 history.back()

    命名视图

          <router-view class="view one"></router-view>
          <router-view class="view two" name="a"></router-view>
          <router-view class="view three" name="b"></router-view>
          
          {
          path: '/',
          components: {
            default: Foo,
            a: Bar,
            b: Baz
          }
    

    导航守卫

    用来通过跳转或取消的方式守卫导航。有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的。

    1.全局守卫

       const router = new VueRouter({ ... })
       router.beforeEach((to, from, next) => {
           // ...
       })
    

      to: Route: 即将要进入的目标(路由对象)

      from: Route: 当前导航正要离开的路由

      next: Function: 确保要调用 next 方法,否则钩子就不会被 resolved。。
      ------next(): 进行管道中的下一个钩子。
      ------next(false): 中断当前的导航。
      ------next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。

      ------next(error):

    2.全局后置钩子

      不会接受 next 函数也不会改变导航本身:

       router.afterEach((to, from) => {
           // ...
       })
    

    3.路由独享守卫

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

    4.组件内的守卫

      beforeRouteEnter
      beforeRouteUpdate (2.2 新增)
      beforeRouteLeave

     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` 访问组件实例
      })
    }
    

    完整的导航解析流程

    导航被触发。
    在失活的组件里调用离开守卫。
    调用全局的 beforeEach 守卫。
    在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
    在路由配置里调用 beforeEnter。
    解析异步路由组件。
    在被激活的组件里调用 beforeRouteEnter。
    调用全局的 beforeResolve 守卫 (2.5+)。
    导航被确认。
    调用全局的 afterEach 钩子。
    触发 DOM 更新。
    用创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。
    

    路由元信息

              path: 'bar',
              component: Bar,
              meta: { requiresAuth: true }
    

    一个路由匹配到的所有路由记录会暴露为 $route 对象 (还有在导航守卫中的路由对象) 的 $route.matched 数组。因此,我们需要遍历 $route.matched 来检查路由记录中的 meta 字段。

     router.beforeEach((to, from, next) => {
      if (to.matched.some(record => record.meta.requiresAuth)) {
        ....
    

    过渡动效

      <transition>
          <router-view></router-view>
      </transition>
    
      // watch $route 决定使用哪种过渡
      watch: {
          '$route' (to, from) {
              const toDepth = to.path.split('/').length
              const fromDepth = from.path.split('/').length
              this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
          }
       }
    

    在导航完成之前获取数据

     beforeRouteEnter (to, from, next) {
        getPost(to.params.id, (err, post) => {
          next(vm => vm.setData(err, post))
        })
      },
      // 路由改变前,组件就已经渲染完了
    

    滚动行为

    当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样

       const router = new VueRouter({
          routes: [...],
          scrollBehavior (to, from, savedPosition) {
                // return 期望滚动到哪个的位置
          }
        })
    
  • 相关阅读:
    Leetcode Reverse Words in a String
    topcoder SRM 619 DIV2 GoodCompanyDivTwo
    topcoder SRM 618 DIV2 MovingRooksDiv2
    topcoder SRM 618 DIV2 WritingWords
    topcoder SRM 618 DIV2 LongWordsDiv2
    Zepto Code Rush 2014 A. Feed with Candy
    Zepto Code Rush 2014 B
    Codeforces Round #245 (Div. 2) B
    Codeforces Round #245 (Div. 2) A
    Codeforces Round #247 (Div. 2) B
  • 原文地址:https://www.cnblogs.com/thing/p/9506890.html
Copyright © 2011-2022 走看看