19/3/31进修笔记

vue-router
1 router-link 导航到差别组件
<router-link to=”/foo”>Go to Foo</router-link>
<router-link to=”/bar”>Go to Bar</router-link>
定义路由
const routes = [
{ path: ‘/foo’, component: Foo },
{ path: ‘/bar’, component: Bar }
]
当 <router-link> 对应的路由婚配胜利,将自动设置 class 属性值 .router-link-active

2 动态路由婚配
routes: [

// 动态途径参数 以冒号开首
{ path: '/user/:id', component: User }

]
3 嵌套路由 ,在组件中还包括多个子组件且存在路由跳转
routes: [

{ path: '/user/:id', component: User,
  children: [
    {
      // 当 /user/:id/profile 婚配胜利,
      // UserProfile 会被渲染在 User 的 <router-view> 中
      path: 'profile',
      component: UserProfile
    },
    {
      // 当 /user/:id/posts 婚配胜利
      // UserPosts 会被渲染在 User 的 <router-view> 中
      path: 'posts',
      component: UserPosts
    }
  ]
}

]

4 编程式导航
除了能够经由过程<router-link to: >跳转,还能够经由过程 this.$router.push() 的体式格局跳转(注重path的体式格局,params不能见效)
// 字符串
router.push(‘home’)

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

// 定名的路由
router.push({ name: ‘user’, params: { userId: ‘123’ }})

// 带查询参数,变成 /register?plan=private
router.push({ path: ‘register’, query: { plan: ‘private’ }})
注重:假如供应了 path,params 会被疏忽,上述例子中的 query 并不属于这类状况。取而代之的是下面例子的做法,你须要供应路由的 name 或手写完全的带有参数的 path:
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

this.$router.replace()
router.replace(location, onComplete?, onAbort?)
跟 router.push 很像,唯一的差别就是,它不会向 history 增加新纪录,而是跟它的方法名一样 —— 替换掉当前的 history 纪录。

5 重定向

重定向

重定向也是经由过程 routes 设置来完成,下面例子是从 /a 重定向到 /b:

const router = new VueRouter({
routes: [

{ path: '/a', redirect: '/b' }

]
})
重定向的目的也能够是一个定名的路由:

const router = new VueRouter({
routes: [

{ path: '/a', redirect: { name: 'foo' }}

]
})

6 导航守御
全局前置守御
你能够运用 router.beforeEach 注册一个全局前置守御:

const router = new VueRouter({ … })

router.beforeEach((to, from, next) => {
// …
})

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

7 路由元信息
定义路由的时刻能够设置 meta 字段:

const router = new VueRouter({
routes: [

{
  path: '/foo',
  component: Foo,
  children: [
    {
      path: 'bar',
      component: Bar,
      // a meta field
      meta: { requiresAuth: true }
    }
  ]
}

]
})

    原文作者:ymuping
    原文地址: https://segmentfault.com/a/1190000018717538
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞