【问题标题】:Vue JS - How to get user id when clicking on a checkbox and then clicking on a buttonVue JS - 单击复选框然后单击按钮时如何获取用户ID
【发布时间】: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>

【问题讨论】:

    标签: javascript arrays vue.js vuejs2


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多