如何将@click事件与选项(vue)一起使用



我想在选项中使用@click事件。在vue上。

这是我的vue代码;

<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>

它适用于Mozilla,但不适用于chrome或其他浏览器。我尝试将@change方法与select一起使用,但我无法发送"值";作为对象。

我该怎么修?

不能只将事件绑定到选项。您可以将@change绑定到<select>,如下例所示。

为选项键提供id(或一些唯一的基元值(也是一个好主意。

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>

检查以下代码

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>

最新更新