[Vuejs]-Vue JS – How to get user id when clicking on a checkbox and then clicking on a button

3👍

Seems you want to collect the checked user IDs. To do so, you should bind your checkbox models to an array and set the value to the 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>

See https://v2.vuejs.org/v2/guide/forms.html#Checkbox

👤Phil

Leave a comment