「这是我参与2022首次更文挑战的第4天,活动详情查看:2022首次更文挑战」
动态路由匹配
我们经常需要把某种模式匹配到的所有路由,都映射到同一个组件,例如,我们有一个demo组件,对于所有id各不相同的文章,都要用这个组件来渲染;此时我们就可以在vue-router的路由路径中使用动态参数来达到这个效果。
先来看一个简单例子
const Demo = {
template: '<div>demo</div>'
};
const router = new VueRouter({
routes: [
{path: 'article/:id', component: Demo}
];
})
现在 article/1 article/2 都会匹配到demo组件。
路径参数使用:标记时,参数会被设置到this.$route.params中,此时在组件中可以通过以下方式来获取参数值
const Demo = {
template: '<div>当前文章的id为 {{$route.params.id}}</div>'
}
当使用路由参数时,从 article/1 到 article/2 时,因为渲染的是同一个组件,所以组件会被复用,这也就会导致组件的生命周期不会在被调用。复用组件时,相对路由参数的变化做出响应的话,我们可以监听路由的变化。
const Demo = {
template: '<div>我是文章详情</div>',
watch: {
$route(to, from) {
// 对路由变化做出响应
}
}
}
也可以使用导航守卫beforeRouteUpdate,在路由发生变化时,都会执行
const Demo = {
template: '<div>我是文章详情</div>',
beforeRouteUpdate(to, from, next) {
}
}
匹配通配符路由
当使用一个通配符时,$route.params内自动添加一个pathMatch参数,它包含了url通过通配符匹配的部分
[
{path: '*'},
{path: '/article-*'}
]
this.$route.push('/article-name');
this.$route.params.pathMatch; // name
this.$route.push('admin');
this.$route.params.pathMatch; // admin
路由的导航守卫
全局守卫
前置守卫
const router = new VueRouter({...});
router.beforeEach((to, from, next) => {
// ...
})
后置守卫
router.afterEach(((to, from) => {
})
路由独享的守卫
你可以在路由配置上直接定义beforeEnter守卫
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
组件内的守卫
const Foo = {
template: '...',
beforeRouteEnter(to, from, next) {
},
beforeRouteUpdate(to, from, next) {
},
beforeRouteLeave(to, from, next) {
}
}