ibrahimcankarta
ibrahimcankarta

Reputation: 15

How can i use @click event with option (vue)

I want to use @click event in option. on vue.

here's my vue code;

<div
  v-for="index in fields"
         :key="index"
>
 <select>
  <option @click="myFunction(index + 1, user)" v-for="user in filteredUsers"
           :key="user"
           :value="user">
           {{ user?.fullName }}
  </option>
 </select>
</div>

it works on Mozilla but not works on chrome or the other browsers. i try to use @change method with select but i can't send "value" as an object.

How can i fix it?

Upvotes: 0

Views: 754

Answers (2)

Daniil8k
Daniil8k

Reputation: 161

You can't just bind an event to an option. You can bind @change to the <select> as in the example below.

It's also a good idea to provide an id (or some unique primitive value) to your option key.

var app = new Vue({
  el: "#app",
  data() {
    return {
      fields: [1, 2],
      filteredUsers: [
        { id: "user_1", fullname: "Susan Harris" },
        { id: "user_2", fullname: "Helen Thomas" },
        { id: "user_3", fullname: "Luis Scott" },
      ],
    };
  },
  methods: {
    myFunction(obj, index) {
      console.log(JSON.parse(obj), index);
    },
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="index in fields" :key="index">
    <select @change="myFunction($event.target.value, index)">
      <option
        v-for="user in filteredUsers"
        :key="user.id"
        :value="JSON.stringify(user)"
      > {{ user?.fullname }}
      </option>
    </select>
  </div>
</div>

Upvotes: 1

Amaarockz
Amaarockz

Reputation: 4684

Check the below code

var app = new Vue({
  el: "#app",
  data() {
    return {
      fields: [1, 2],
      filteredUsers: [
        { id: "u1", fullname: "Steve" },
        { id: "u2", fullname: "Tony" },
        { id: "u3", fullname: "Strange" },
      ],
    };
  },
  methods: {
    myFunction(obj, index) {
      console.log(obj.target.value, index); // Change added
    },
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="index in fields" :key="index">
    <select @change="myFunction($event, index)"> <!-- change added -->
      <option
        v-for="user in filteredUsers"
        :key="user.id"
        :value="user.fullname"
      > {{ user.fullname }}
      </option>
    </select>
  </div>
</div>

Upvotes: 0

Related Questions