Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass dynamic data to router-link.

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.

PARENT COMPONENT

<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?

like image 560
Bitwise Avatar asked Apr 20 '18 15:04

Bitwise


1 Answers

Using Dynamic Route Parameters

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>


Directly using variable with 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.


Using query parameters

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.

like image 131
Derek Pollard Avatar answered Nov 10 '22 09:11

Derek Pollard