Dynamic routing configuration
Like /user/foo
and /user/bar
are mapped to the same route. That is according to the different ID
, the same rendering User
components. Use dynamic path parameters to achieve this effect.
Dynamic Route parameter colon :
mark, followed by the name of the parameter, the parameter will be set to this.$route.params
the.
<script>
// 匹配模式
/user/:username
// 匹配到的路径为
/user/evan
// $route.params 获取到的参数对象
{ useranme: 'evan' }
</script>
Note: with :
the configuration of the colon can be understood as a regular match, so you can set up a final ?
inert match, that can occur 0 or 1 times.
Corresponding change of route parameters
When using the routing parameters, such as from /user/foo
navigating to /user/bar
, the original component instance are multiplexed . Because both routes are rendering the same component, and then create than destroy, reuse is even more efficient. This also means that the components of the life cycle of the hook function will not be called .
When reusable component, the relative change in the routing parameters accordingly, it may be used watch
(monitoring) $route
object changes. You can also use beforeRouteUpdate
the navigation routing updates guards.
<script>
const User = {
template: '...',
// 1. 通过监听路由对象变化的形式
watch: {
'$route' (to, from) {
// 对路由变化作出响应
}
},
// 2. 通过更新路由的钩子函数
beforeRouteUpdate (to, from, next) {
// 路由变化会触发...
}
}
</script>
Capture all routes or route 404 Not found
Any path matches using wildcard (*); Note: using wildcards routes, must be placed in the final configuration. Typically used for client 404.
<script>
{ path: '*' } // 会匹配所有路径
{ path: '/user-*' } // 会匹配以 /user- 开头的任意路径
</script>
When using a wildcard, $route.params
inside will automatically add a named pathMatch
parameter. Note:pathMatch
to obtain a *
content part
<script>
// { path: '/user-*' }
this.$router.push('/user-admin');
this.$router.params // 获取到的是 { pathMatch: 'admin' }
</script>