Vue Router(2)

写在前面

在上一篇博客 Vue Router(1) 中介绍了 Vue Router 的基本使用方法,在本篇博客将继续深入 Vue Router,解锁更多的功能。

1. 编程式导航

Vue Router 里的编程式导航简单来说,就是,如果我们不用 <a> 标签来定义导航链接,那该如何跳转页面呢?那就需要使用 JavaScript 编程语言来操控接口进行导航。

在原生的 Web API 中,除了 a 标签外,我们通常使用 window.location.href = "/xxx" 或者 window.open("xxx") 来跳转页面。若想改变 url 但不刷新页面,就需要使用 Web API 中 History接口新增的跳转方法。在 前端路由 中有详细介绍。就是 window.history.pushState() 和 window.history.replaceState(),在 Vue Router 的内部就是使用了这两个接口,只不过 Vue Router 进行了封装,在 Vue Router 实例中留出了对应的接口。就是 router.push()

以下小例来自 Vue Router 官网。同样的规则也适用于 router-link 组件的 to 属性。

// 字符串
router.push('home')

// 对象
router.push({ path: 'home' })

// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})

// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

const userId = '123'
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 这里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user

2. 导航守卫

导航守卫主要用来通过跳转或取消的方式守卫导航,说人话就是,导航守卫就是在路由跳转的过程中执行的特殊的钩子函数。路由跳转看似就是一瞬间的事,但其实被划分成了各个阶段,在各个阶段都有提供特殊的函数,当路由跳转时被自动调用。

就好像原生的 Web API 中的 window.onbeforeunload / window.onload / window.onunload 这样的 API。

image

2.1 全局守卫

1. router.beforeEach((to, from, next) => {
  // ...
})
2. router.beforeResolve(to, from, next) => {
  // ...
})
3. router.afterEach((to, from) => {
  // ...
})

2.2 路由独享的守卫

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

2.3 组件内的守卫

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`
  }
}

3. 路由懒加载

路由懒加载的意思就说,我们并不在一开始就把所有要用到的组件都 import 进来。而是在路由跳转至对应的组件时才将该组件加载进来。这样会更高效。

懒加载前:

import A from './components/A.vue'
import B from './components/B.vue'

const routes = [
  {path: '/a', component: A},
  {path: '/b', component: B}
]

懒加载后:

const A = () => import('./components/A.vue')
const B = () => import('./components/B.vue')

const routes = [
  {path: '/a', component: A},
  {path: '/b', component: B}
]
```
原文地址:https://www.cnblogs.com/lovevin/p/13476941.html