- 动态路由匹配 某种模式匹配到的所有路由(url)映射到同个组件,被称为动态路由参数。路由配置:
new Router({
routes: [{
path: 'home/:id',
name:'home',
component: Home
}]
})
而组件中通过$route.params.id
获取。
为了降低耦合,减少使用 $route.params.id
,可将路由配置做出如下修改:
new Router({
routes: [{
path: 'home/:id',
name:'home',
component: Home,
props: true
}]
})
在路由映射的组件可以直接通过id
获取而非$route.params.id
。除了props模式,还有对象模式,和函数模式。目的是:一次在route配置中设置完成,在映射的路由组件中将减少使用$route.params.id
- 嵌套路由
vue-route中路由抽象为:组件与路由地址的映射,
parent & child route
映射到parent & children Component
。目的是让views下面的组件依据搜索框search bar对应的url对应渲染。所有的组件统一渲染在App.vue
,即:
<div id="app">
<router-view />
</div>
需要在main.js
将router配置在new Vue实例中即
new Vue({
el: "#app",
router,
render: h=> h(App)
})
一般来说,项目启动会默认打开path: "/"
,渲染路由为/
的组件。如果想要在该组件继续通过route进行渲染子组件。需要在vue-route进行配置children,父组件中引入<router-view />
便可在父组件中渲染对应的子组件。
- 命名组件 组件中书写
<router-view name="smoe"></router-view>,
<router-view name="other"></router-view>,
路由中配置
new Router({
routes: [{
path: 'home/:id',
name:'home',
components: {
some:Home.
other: Other
},
}]
})
概括来说,一个路由匹配后,同时渲染出多个同级组件view。场景为:一个整体布局。
- 路由重定向可用来授权登录前的验证判断。
- 路由跳转,可以是
<router-link :to="path:/home"></router-link>
也可是this.$router.push({name: 'commit', params: {id: 12}})
也可以this。$router.push({name: 'commit', query: {plan: private}})
。最终在页面获取的方式是$route.params.id
或者$route.query
,另外router.replace(location, onComplte?, onAbort?)
不会像history添加新纪录。路由返回按钮,可以通过router.go()
实现前进或者后退。