According to official docs
Sometimes it is more convenient to identify a route with a name, especially when linking to a route or performing navigations.
So, how is this can be more convenient?
<router-link :to="{ name: 'user', params: { id: user.id }}">
{{ user.name }}
</router-link>
vs
<router-link :to="'/user/' + user.id">
{{ User.name }}
</router-link>
I feel like I'm missing something obvious.
Vue Router is the official router for Vue. js. It deeply integrates with Vue. js core to make building Single Page Applications with Vue.
You need a router when you need to sync URLs to views in your app. It's a very common need, and all the major modern frameworks now allow you to manage routing. The Vue Router library is the way to go for Vue. js applications.
To navigate to a different URL, use router.push . This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.
Instead of having one single outlet in your view, you can have multiple and give each of them a name. A router-view without a name will be given default as its name. A working demo of this example can be found here.
I always use named routes.
The advantage is that you can change the path of the route without needing to change the path in every <router-link>
or this.$router.push()
call.
It's kind of like the reason why, in programming, we avoid magic values and instead use named constants – we can change the value in one place without needing to find-and-replace all occurrences of the value in our code.
Without using named routes, your code becomes tightly bound to the path of each route, you can't change one without needing to change the other. Named routes makes our code independent of the route paths – it'll work whatever the path of the route ends up being.
Another advantage is we can take advantage of param/query inheritance for nested routes – we don't need to reconstruct the full path, instead we can just pass the name of the child route and Vue will construct the full path with any existing params.
Suppose we have the following routes:
{
name: 'user',
path: '/user/:id',
children: [
{
name: 'profile',
path: 'profile'
}
]
}
and the current route path is /user/1
. To go to the profile page, we need to do either:
this.$router.push({ name: 'profile' })
or
this.$router.push('/user/' + this.$route.params.id + '/profile')
The former is simpler and less error prone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With