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?
CodePudding user response:
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.
<template>
<div id="app">
<div v-for="index in fields" :key="index">
<select @change="(e) => myFunction(e.target.value, index)">
<option
v-for="user in filteredUsers"
:key="user.id"
:value="JSON.stringify(user)"
>
{{ user.fullname }}
</option>
</select>
</div>
</div>
</template>
<script>
export default {
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>
CodePudding user response:
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>