Vue JS - 单击复选框然后单击按钮时如何获取用户ID
Posted
技术标签:
【中文标题】Vue JS - 单击复选框然后单击按钮时如何获取用户ID【英文标题】:Vue JS - How to get user id when clicking on a checkbox and then clicking on a button 【发布时间】:2021-09-22 09:29:38 【问题描述】:我有自己的复选框的用户,我需要这样做,当您通过单击复选框选择特定用户时,然后当您单击“获取用户 ID”按钮时,在 getUserId 方法中获取用户 ID .
这里是code in CodeSandbox
<template>
<div>
<div class="user" v-for="(user, i) in items" :key="i">
<p> user.name </p>
<p> user.age </p>
<input type="checkbox" />
</div>
<button @click="getUserId()">Get user id</button>
</div>
</template>
<script>
export default
methods:
getUserId() ,
,
data()
return
items: [
id: 1,
name: "Alex",
age: 23,
,
id: 2,
name: "Robert",
age: 33,
,
id: 3,
name: "Jacob",
age: 55,
,
],
;
,
;
</script>
【问题讨论】:
【参考方案1】:您似乎想收集 已检查 的用户 ID。为此,您应该将复选框 models 绑定到一个数组,并将 value
设置为 user.id
new Vue(
el: "#app",
methods:
getUserId()
console.log("userIds", this.userIds)
,
,
data()
return
items: ["id":1,"name":"Alex","age":23,"id":2,"name":"Robert","age":33,"id":3,"name":"Jacob","age":55],
userIds: [] // start with an empty array
,
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<!-- Note: the `user.id` makes for a much better `key` -->
<div class="user" v-for="user in items" :key="user.id">
<p> user.name </p>
<p> user.age </p>
<!-- Set the checkbox value to `user.id` and bind the model to your array -->
<input type="checkbox" :value="user.id" v-model="userIds" />
</div>
<button @click="getUserId()">Get user id</button>
</div>
见https://vuejs.org/v2/guide/forms.html#Checkbox
【讨论】:
以上是关于Vue JS - 单击复选框然后单击按钮时如何获取用户ID的主要内容,如果未能解决你的问题,请参考以下文章
为啥在单击“全选”按钮后,复选框会被选中,然后又被取消选中?