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
},
router.push(‘home‘) // 字符串
router.push({ path: ‘home‘ }) // 对象
router.push({ name: ‘user‘, params: { userId: 123 }}) // 命名的路由
router.push({ path: ‘register‘, query: { plan: ‘private‘ }}) // 带查询参数,变成 /register?plan=private
原文:https://www.cnblogs.com/thing/p/9506890.html