How to pass methods e.g @click="someMethod" to a specific dynamic navbar router-link generated with v-for?

Hey guys, simple question here, I don’t know if this is possible or not.

I have a list of router-links in my navbar menu that get generated from a data-set with v-for.

How can i pass a method to one or some of those links? For example i want to pass a `@click=“logOut” method to one of those links. Is this possible?
Some of the links are supposed to perform some functions instead of just routing.

This is how i generate the links with v-for…

<div v-for="link in menuLinks" :key="link.id">
  <router-link to>
     <span>{{ link.link }}</span>
  </router-link>
</div>
data() {
    return {
      menuLinks: [
        {
          link: "CART",
          id: 1
        },
        {
          link: "PRODUCTS",
          id: 2
        },
        {
          link: "LOGOUT",
          id: 3
        }
      ]
    };
  },

Hi

You could do something like this. Links which define method will run it on clicking. Prevent on @click prevents the default behavior to go to url in href.

<div v-for="link in menuLinks" :key="link.id">
 <a v-if="link.method != undefined" href="" @click.prevent="link.method"> {{ link.link }}</a>
  <router-link v-else to>
     <span>{{ link.link }}</span>
  </router-link>
</div>

and in data:

{
          link: "LOGOUT",
          id: 3,
          method: this.logout
 }

and then in methods:

logout() {
  alert('Logged out')
}
2 Likes

Thanks @johandalabacka :slight_smile:
I had to tweak things a little but you gave me the right idea to work on. Thanks

1 Like

I’m curious as to why the same v-if/v-else cannot be applied to the router-link? I tried it with router-link and it didn’t work but i tried it with the <a> tag as you suggested and it worked.

What i mean is to have v-if router-link & v-else router-link instead of v-if <a> & v-else router-link
I have some assumptions on why this is the way it is, but not entirely sure.

Great solution anyway. I just really want to understand why it works the way it does. Thanks again. :slight_smile: