vue-router dynamic routing matching
We often need to map all routes that a certain pattern matches to the same component.
For example, we have aUser
Components, for all users with different IDs, use this component to render.
Then, we canvue-router
Use "dynamic segment" in the routing path to achieve this effect:
In short, dynamic routing matching solvesPage jumps according to idThe problem
// appfront/src/router const User = { template: '<div>User</div>' } const router = new VueRouter({ routes: [ // Dynamic path parameters begin with a colon { path: '/user/:id', component: User } ] })
Now, like/user/foo
and/user/bar
All will be mapped to the same route.
A "path parameter" uses a colon:
mark. When a route is matched, the parameter value is set tothis.$
, can be used within each component.
So, we can updateUser
template, output the current user's ID:
const User = { template: '<div>User {{ $ }}</div>' }
You can set multiple "path parameters" in a route, and the corresponding values will be set to$
middle.
For example:
model | Match paths | $ |
---|---|---|
/user/:username | /user/evan | { username: 'evan' } |
/user/:username/post/:post_id | /user/evan/post/123 | { username: 'evan', post_id: '123' } |
Apart from$
outside,$route
The object also provides other useful information, for example,$
(If there are query parameters in the URL),$
etc.
You can viewAPI DocumentationDetailed description
The following is a page that uses dynamic routing to jump to the corresponding page in actual applications (the button is used here, and you can also jump to route-link here and skip it).
// components/ ... <el-button size="mini" @click="handleEdit()">edit</el-button> ... <script> export default { methods: { handleEdit(Id) { # Jump to xxx+id page this.$({path:'/xxx/'+Id}) }, </script>
// router/ ... import Router from 'vue-router' import xxx from '@/components/xxx' ... export default new Router({ routes: [ ... { path:'/xxx/:Id', name:'xxx', component: xxx }, ... ] })
Get parameters after jump
// components/ ... <div>{{ this.$ }}</div> ...
refer to:
Vue Route official documentation
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.