- This is the 20th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021
VueRouter_ Dynamic route matching
When we need to map all the routes that a pattern matches to the same component. For example, we have a User component that is used to render for all users with different ids. We can use dynamic path parameters in vue-Router routing paths to achieve this effect:
const User = {
template: '<div>User</div>'
}
const router = new VueRouter({
routes: [
// Dynamic path parameters start with a colon
{ path: '/user/:id'.component: User }
]
})
Copy the code
With this setup, things like /user/foo and /user/bar are mapped to the same route.
A “path parameter” uses the colon: notation. When a route is matched, the parameter value is set to this.$route.params, which can be used within each component.
VueRouter_ Named View – Route component parameter transmission
Named view
You can use named views when you want to show multiple views at the same time, and each view shows a different component.
Instead of having a single exit, you can have multiple individually named views in the interface. If router-view does not have a name, it defaults to default.
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
Copy the code
A view renders with one component, so multiple views require multiple components for the same route. Make sure to use the Components configuration correctly (with s) :
const router = new VueRouter({
routes: [{path: '/'.components: {
default: Foo,
a: Bar,
b: Baz
}
}
]
})
Copy the code
Route component parameters are transmitted
Using $route in a component makes it highly coupled to its corresponding route, limiting its flexibility by limiting its use to certain urls.
Decouple components and routes using props.
The Boolean model
If props is set to true, route.params will be set to the component property.
Object pattern
If props were an object, it would be set as a component property as is. This is useful when props is static.
const router = new VueRouter({
routes: [{path: '/promotion/from-newsletter'.component: Promotion,
props: { newsletterPopup: false}}}])Copy the code
The function mode
You can create a function that returns props. The first argument to the function is route (that is, $route).
const router = new VueRouter({
routes: [{path: '/search'.component: SearchUser, props: (route) = > ({ query: route.query.q }) }
]
})
Copy the code
The last
If it is helpful to you, I hope to give you a 👍 comment/collection/three even!
Bloggers are honest and answer questions for free ❤