vue第十五单元(熟练使用vue-router插件)

第十五单元(熟练使用vue-router插件)

#课程目标

1、掌握路由嵌套

2、掌握导航守卫

#知识点

#一、路由嵌套

很多时候,我们会在一个视口中实现局部页面的切换。这时候就需要到了嵌套路由。

也就是说一个被渲染组件同样可以包含自己的嵌套 <router-view>

const router = new VueRouter({
  routes: [
    { path: '/cinema', //电影
      component: Cinema,
      children: [ 
        {
          path: 'hot', //正在热映
          component: Hot
        },
        {
          path: 'ing', //即将上映
          component: Ing
        }
      ]
    }
  ]
})
注意:二级路由的path不加/会从父路由找起,加/会从跟路由找起
 

1573617020905

#二、导航守卫

共有三种守卫:全局的, 单个路由独享的, 或者组件级的。

1、全局前置守卫

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // ...
})
 
  • to: Route: 即将要进入的目标 路由对象

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

  • next: Function:

    ​ next(false)中断当前导航

    ​ next('/') 或者 next({ path: '/' }) 跳转到其他路由

    ​ 确保要调用 next 方法,否则钩子就不会被 resolved

2、全局后置钩子

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

3、路由独享的守卫

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

4、组件内的守卫

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

    不过,你可以通过传一个回调给 next来访问组件实例

  • beforeRouteUpdate (2.2 新增)

  • beforeRouteLeave

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

案例讲解:美团外卖:进入收藏页面前,进行路由守卫:如果当前用户已登录则进入收藏,否则进入登录页面。

#授课思路

15.vue-router高级

#案例作业

一、花礼网

1573618910650

posted @ 2020-12-14 10:59  人心不古  阅读(86)  评论(0)    收藏  举报