[Vuejs]-Adding functional checkboxes to a list of users in Vue

0👍

Add the checked property to your user objects after they have been retrieved via AJAX.

console.clear()

// simulated data from the server
const users = [
  {id: 1, username: "Bob"},
  {id: 1, username: "Mary"},
]

new Vue({
  el: "#app",
  data:{
    users:[]
  },
  computed:{
    filteredUsers(){
      // simulate filtered users
      return this.users
    }
  },
  methods:{
    getUsers(){
      // simulate an ajax call with setTimeout
      setTimeout(() => {
        // iterate over the user objects retrieve from the server
        // and add a checked property. Assign the result to users
        this.users = users.map(u => Object.assign({}, u, {checked: false}))
      }, 250)
    }
  },
  created(){
    this.getUsers()
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
  <table>
    <tr v-for="guser in filteredUsers" class="group_user">
      <td><input type="checkbox"v-model="guser.checked"></td>
      <td>{{guser.username}}</td>
    </tr>
  </table>
  {{users}}
</div>

The reason it doesn’t work initially is because Vue cannot detect properties dynamically added to an object after that object has already been added to Vue. Another way to handle this would be to use the $set method to add the property (instead of Object.assign as I do in the example).

👤Bert

Leave a comment