Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get clicked item in vue

Tags:

I'm trying to do basic something but i can't figure out.

i have a dropdown:

<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" v-model="selectedItem">
      <a class="dropdown-item" v-for="item in items">
        {{item.name}}
      </a>
    </div>
  </div>
</div>


var app = new Vue({
  el: '#app',
  data: {
    selectedItem: null,
     items: [
     {
         name: "Dropdown Item"
     },
     {
         name: "Dropdown Item 2"
     },
     {
         name: "Dropdown Item 3"
     }
    ]
  },
});

Basically i'm trying to do when clicked to dropdown item it will be {{selectedItem}} for that i have tried to use v-model in my menu wrapper but nothing happened.

like image 448
user3348410 Avatar asked Dec 12 '18 07:12

user3348410


1 Answers

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)

like image 87
mrrrk Avatar answered Oct 03 '22 02:10

mrrrk