[Vuejs]-Dynamic binding of v-model inside v-for loop

1πŸ‘

βœ…

In your case <input type="checkbox" v-model="perm.perm"> is enough to make it work.

I would suggest a bit of refactoring and renaming though, sinde perm.perm shows how unintuitive your current data structure and naming is.

I’d suggest to use a computed property to return the userPermissions instead of accessing the array by index in the template.
Also consider renaming your object properties to something like permissions and isAllowed to be more clear.

computed: {
  ...
  userPermissions() {
    let index = this.getUserIndex()
    // TODO: handle null
    return this.users[index].permissions
  }
}

And in your template

<li v-for="p in userPermissions">
  <span>{{ p.status }}</span>
  <input type="checkbox" v-model="p.isAllowed">
</li>
πŸ‘€TommyF

0πŸ‘

This should works.

new Vue({
  el: "#app",
  data: {
    users: [{
        name: 'Alex',
        perms: [{
            status: 'active',
            perm: false
          },
          {
            status: 'invoice',
            perm: false
          }
        ]
      },
      {
        name: 'John',
        perms: [{
            status: 'active',
            perm: false
          },
          {
            status: 'invoice',
            perm: false
          }
        ]
      },
      {
        name: 'Helen',
        perms: [{
            status: 'active',
            perm: false
          },
          {
            status: 'invoice',
            perm: false
          }
        ]
      },
    ],
    selectedUser: ''
  },
  computed: {
    getUserIndex() {
      let username = this.selectedUser;
      let index = this.users.findIndex(el => el.name === username);
      if (index == -1) {
        return null
      } else {
        return index
      }
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select v-model="selectedUser">
    <option value="" disabled>Select User</option>
    <option v-for="user in users" :value="user.name">{{ user.name }}</option>
  </select>
  <p>User Index: {{ getUserIndex }}</p>
  <ul v-if="getUserIndex !== null ">
    <li v-for="(item, id) in users[getUserIndex].perms">
      <span>{{ item.status }}</span>
      <input type="checkbox" v-model="item.perm">
    </li>
  </ul>
</div>
πŸ‘€tuhin47

Leave a comment