[Vuejs]-Vue v-for index undefined in array object

0๐Ÿ‘

โœ…

You could use some to iterate over the other array and check whether any of the entries match the current row:

:checked="user_permissions.some(perm => perm.name === row.name)"

For small arrays this should be fine. For larger arrays you could speed it up by replacing the inner array with an object that has the permission names as keys and all the values as true. Such an object could be created as a computed property and would allow you to skip the inner loop.

0๐Ÿ‘

Multiple selection of checkbox must be in the form of array model.

When you insert the value of permissions, you must insert the result into the checkbox model after comparison.

ex)

<div v-for="(row, index) in permissions">
  <input
    v-model="model"  // array type
    type="checkbox"
    :key="index"
    :value="row.name"
  />{{row.name}}
</div>

Example code was created in the pen below.
pen โ€“ https://codepen.io/kdydesign/pen/QWWwBmx?editors=1111

0๐Ÿ‘

I have just cooked something by looking at your data and code. I have not tested it myself but I hope you can see what am trying to do.

<template>
    <div class="form-group">
        <div class="alert alert-success" v-if="alert_permission">Izin telah diberikan</div>
            <input
              type="checkbox"
              class="flat-red new-select"
              v-model="selectedPermissions"
              v-for="permission in permissions"
              :key="permission.id"
              :checked="userHasPermission(permission.name)"
              :value="permission.name"
              @click="addPermission(permission.name)"
            />{{ permission.name | ucwords }}
        </div>
    </div>
</template>

<script>
export default {
    data: function () {
        return {
            selectedPermissions: [],
            permissions; [],
            user_permissions: [],
        }
    },
    mounted ()  {
        // this.permissions = /* call api service to get all permissions */
        // this.user_permissions = /* call api service to get user permissions */
    },
    filters: {
        ucwords (value) {
            const words = String(value).split(/\s+/)
            return words.map(word => {
                let temp = word.trim() 
                return temp.charAt(0).toUpperCase() + temp.slice(1)
            }).join(' ');
        },
    },
    methods: {
        userHasPermission (permissionName) {
            let index = this.user_permissions.findIndex((user_permission) => {
                return user_permission.name === permissionName
            })

            return index !== -1
        },

        addPermission (permissionName) {

        }
    }

}
</script>

I hope it helps.

Leave a comment