How get clicked item in vue
Building on Kumar's answer, you can access the event in the handler method by default as long you do not pass any other parameters.
However, if you do pass a parameter then it seems you have to pass the event explicitly using $event
:
<button @click="doStuff('whatever', $event)">Do Stuff</button>
...
doStuff(whatever, event) {
console.log(event.target);
}
If you're going to use the event object, it's probably better to pass it explicitly rather than rely on the default. Or not, depending on your point of view. It's a toss-up between making things clear or saving on typing!
<!-- this works -->
<button @click="doStuff">Do Stuff</button>
<!-- this works too -->
<button @click="doStuff($event)">Do Stuff</button>
...
doStuff(event) {
console.log(event.target);
}
(I tried these out with Vue 2.6)
We can also use ES6 syntax abbreviation via the methods:
... template
<a @click="expand" data-toggle="collapse" aria-expanded="false">{{ menuItem.title }}</a>
... more template
... script section
methods: {
expand({ target }) {
console.log('this is the element i clicked: ', target);
}
}
... more script code
You cannot use v-model
with div
here.
Instead, You should use v-click
to call a method in order to update value selectedItem
and handle toggle action.
One more thing, When you use v-for
you should have key id
which is recommended by Vuejs.
Just draft implementation:
<div class="dropdown is-active">
<div class="dropdown-trigger">
<button class="button" aria-haspopup="true" aria-controls="dropdown-menu">
<span>{{selectedItem}}</span>
</button>
</div>
<div class="dropdown-menu" id="dropdown-menu" role="menu">
<div class="dropdown-content">
<a class="dropdown-item" v-for="item in items" :key="item.id" v-click="handleSelectItem(item)">
{{item.name}}
</a>
</div>
</div>
</div>
var app = new Vue({
el: '#app',
data: {
selectedItem: null,
items: [
{
id: 1,
name: "Dropdown Item"
},
{
id: 2,
name: "Dropdown Item 2"
},
{
id: 3,
name: "Dropdown Item 3"
}
]
},
method: {
handleSelectItem(item){
this.selectedItem = item.name;
// you can also handle toggle action here manually to open and close dropdown
}
}
});
you can pass the event to the handler function and access it by event.target
<div class="dropdown-menu" id="dropdown-menu" role="menu">
<div class="dropdown-content" v-model="selectedItem">
<a class="dropdown-item" v-for="item in items" @click="HandlerFunction">
{{item.name}}
</a>
</div>
</div>
var app = new Vue({
el: '#app',
data: {
selectedItem: null,
items: [
{
name: "Dropdown Item"
},
{
name: "Dropdown Item 2"
},
{
name: "Dropdown Item 3"
}
]
},
methods: {
HandlerFunction(event){
console.log(event.target)
}
}
});