0

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?

1
  • it makes sense when you make something real, fields is what your looping over, it should be an array of objects (item), then you use the model <select v-model="item.user">, array of numbers, might as well hardcode 2 inputs Commented Aug 8, 2022 at 15:01

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! :value="JSON.stringify(user)" part is total match for me. it works.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.