Konrad Viltersten
Konrad Viltersten

Reputation: 39268

How to obtain the id (or any other attribute) of the component clicked in Vue template?

I have a setup like this. It's an element being clicked and invoking a method using it's specific string to be recognized. Of course, I'd prefer the ID to be provided so I won't have to maintain the redundant names.

<li id="donkey" v-on:click="clickaroo('donkey');">Donkey</li>
...
methods: {
  ...
  clickaroo: function(event) { console.log(event + " clicked"); }
}

When I went googlearching I've seen here and there that the syntax used was v-on="click: clickaroo" and not as shown in the docs, i.e. v-on:click="clickaroo". The former doesn't seem to work at all, let alone fetching me the right value.

I've also found big nothing and now I'm confused how to resolve the matter. Is it the proper way in Vue to provide the parameter like I do?

Upvotes: 0

Views: 250

Answers (1)

Mihai Vilcu
Mihai Vilcu

Reputation: 1967

You can access the element clicked from the current event.

The code would look something like this

<a v-on:click="myFunction($event, 'param')">Click me</a>

// in your component
methods: {
    myFunction: function(event, param) {
        console.log(event.target);
    }
}

Upvotes: 2

Related Questions