美文网首页
Vue 路由 Vue-Router

Vue 路由 Vue-Router

作者: 李霖弢 | 来源:发表于2019-08-08 09:15 被阅读0次

路由

注入实例
const router = new VueRouter({
  routes : [
    { path: '/user', name: 'user' , component:  { template: '<div>User</div>' },
    { path: '/user/:id', 
       component: { template: '<div>{{ $route.params.id }}</div>' }
    }
  ]
})
new Vue({
  router
}).$mount('#app')

此后可以在任何组件内通过 this.$router 访问路由器(或通过import导入router实例来访问),通过 this.$route 访问当前路由(包括query,hash等)

路由参数

通过:标记路由参数,组件内可通过$route.params访问该参数。
使用props可以将组件和路由解耦,使组件不再只能在特定URL下使用。

嵌套路由

如下,当 /main 匹配成功,Main会被渲染,同时 MainDefault 会被渲染在 Main 的<router-view> 中。当/main/dashboard 匹配成功,Dashboard 会被渲染在 Main 的<router-view> 中

{
  path: '/main',
  name: 'main',
  component: Main,
  children: [
    { path: '', component: MainDefault },
    {
      path: 'dashboard',
      component: Dashboard
    }
  ]
}
捕获所有路由或404路由

通过通配符 * 可匹配所有路径,如需匹配404则应将该路由配置在最后(先配置的路由匹配优先级更高)

{
  path: '*'
}
hostory模式

利用了history.pushState API,使URL中将不再具有#。但需服务器端做好对应配置。

const router = new VueRouter({
  mode: 'history',//默认为hash
  routes: [...]
})
重定向

导航守卫只会对重定向之后的路由生效

  routes: [
    { path: '/a', redirect: '/bar' },
    { path: '/b', redirect: { name: 'foo' }}
  ]
别名

/a 的别名是 /b,意味着,当用户访问 /b 时,URL 会保持为 /b,但是路由匹配则为 /a,就像用户访问 /a 一样。

{ path: '/a', component: A, alias: '/b' }

导航和出口

<router-link> 默认会被渲染成一个 <a> 标签,将匹配到的组件渲染在路由出口<router-view>
以 / 开头的嵌套路径会被当作根路径

<router-link to="/foo">Go to Foo</router-link>
<router-view></router-view>
编程式的导航
  1. router.push(location, onComplete?, onAbort?)
    location可以为对象或字符串。注意当对象使用path时,params会被忽略。
    同样的规则也适用于 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' }})

onCompleteonAbort回调将会在导航成功完成 (在所有的异步钩子被解析之后) 或终止 (导航到相同的路由、或在当前导航完成之前导航到另一个不同的路由) 的时候进行相应的调用

  1. router.replace(location, onComplete?, onAbort?)
    不会向 history 添加新记录
  2. router.go(n)
    传入-1时即为后退
命名出口

同一层级下存在多个视图,可通过name区分,默认为default

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

const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        default: Foo,
        a: Bar,
        b: Baz
      }
    }
  ]
})

导航守卫

触发条件

路由参数(如:id)或查询(query)的改变会复用组件,并不会触发进入/离开的导航守卫,也不会销毁/创建目标组件。因此组件的生命周期也不会触发。此时可以通过以下方式相应路由参数变化:

  1. watch $route 对象
  2. 组件内导航守卫beforeRouteUpdate (to, from, next) {}
触发顺序

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

全局前置守卫 router.beforeEach
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
  // ...
})

当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中。
每个守卫方法接收三个参数:

  • to: Route: 即将要进入的目标路由
  • from: Route: 当前导航正要离开的路由
  • next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
    • next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。

    • next(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。

    • next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: truename: 'home' 之类的选项以及任何用在 router-linkto proprouter.push 中的选项。

    • next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。
      确保要调用 next 方法,否则钩子就不会被 resolved。

全局解析守卫 router.beforeResolve

router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。

全局后置钩子 afterEach

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

router.afterEach((to, from) => {
  // ...
})
路由独享的守卫 beforeEnter
const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})
组件内守卫
  • beforeRouteEnter
  • beforeRouteUpdate
  • 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`
  }
}

路由元信息 meta

可用于存储该路由的一些自定义信息,如权限检测、是否需要登录等。
一个路由匹配到的所有路由记录(包括所有祖先)会暴露为 $route.matched 数组。我们可以遍历 $route.matched 来检查路由记录中的 meta 字段。

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

滚动行为

查看文档

换到新路由时,想要页面滚到指定位置,或者是保持原先的滚动位置,或滚动到目标锚点。

const router = new VueRouter({
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
    // return 期望滚动到哪个的位置
    // `savedPosition` 当且仅当 popstate 导航 (通过浏览器的 前进/后退 按钮触发) 时才可用。
  }
})

路由懒加载

把不同路由对应的组件分割成不同的代码块,当路由被访问的时候才加载对应组件

Webpack自动分割
const Foo = () => import('./Foo.vue')

const router = new VueRouter({
  routes: [
    { path: '/foo', component: Foo }
  ]
})
把组件按组分块

通过命名chunk,一个特殊的注释语法,Webpack 会将相同块名称的异步模块组合到相同的异步块中。

const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue')
const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue')
const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue')

相关文章

网友评论

      本文标题:Vue 路由 Vue-Router

      本文链接:https://www.haomeiwen.com/subject/xsdadctx.html