I'm trying to pass a dynamic path to vue-router but I can't seem to give it the correct syntax. Here is what I'm trying.
<li v-on:click="$emit('closeDropdown')"><router-link to="item.route" id="button">{{ item.title }}</router-link></li>
Is just wrapping it in quotes not enough because this is what I see when I inspect the elements: href="#/item.route"
for all items.
<UserDropdownList v-for="item in userDropdownItems" v-bind:item="item"></UserDropdownList>
data: function () {
return {
userDropdownItems: [
{ title: 'Profile', route: "/profile" },
{ title: 'Users', route: "/users" }
]
}
}
How can I access the route property for the Router-link
to attribute?
If you take a look at the vue-router
documentation, what you're describing sounds very much like a job for dynamic route parameters:
const router = new VueRouter({
routes: [
// dynamic segments start with a colon
{ path: '/user/:id', component: User, name: 'user' }
]
});
Then, to generate a link via <router-link>
for said route, you'd do the following:
<!-- named route -->
<router-link :to="{ name: 'user', params: { id: 123 }}">User</router-link>
router-link
To use variables in a router link, all you have to do is this:
<router-link :to="item.route" id="button">{{ item.title }}</router-link>
Adding a colon (:) before the to
attribute tells Vue that you're about to use some javascript in there.
Instead of using dynamic route parameters OR js variables, you could use the query option instead:
<!-- with query, resulting in `/register?plan=private` -->
<router-link :to="{ path: 'register', query: { plan: 'private' }}">Register</router-link>
Hope this helps! I've attached all the documentation sources where I found this. I highly recommend giving it a solid look through, as it is one of the most well-written documentation sites I've ever come across.
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