Tips for gathering an array of checkboxes within a dynamic array of items using Vue.js and Vuetify

I am currently working on a role permission system where I have defined a resource array containing items that users can access, as well as checks representing the permissions for each resource.

My goal is to dynamically assign a role with these resources and allow users to choose their desired permissions.

However, my current implementation only submits the last selected item from the checkbox instead of an array of all chosen permissions. What could I be missing here?

The template structure is as follows:


<template v-slot:activator="{ on }">
  <v-btn
    class="mx-2"
    data-toggle="tooltip"
    data-placement="left"
    title="Edit Permissions"
    fab
    dark
    small
    color="#666"
    v-on="on"
    @click="getItem()"
  >
    <v-icon dark>mdi-access-point</v-icon>
  </v-btn>
</template>
<v-form v-model="valid" @submit.prevent="onSubmit">
      <v-container>

        <v-row>
          <v-col cols="12" sm="12" md="12" class="alternate-card">
            <h4 class="text-muted text-center">
              Role : {{ payload.role }}
            </h4>
          </v-col>
          <blockquote class="col-md-12">
            <h4 class=" text-center">Permissions</h4>
          </blockquote>
          <hr />
          <v-col
            cols="12"
            sm="12"
            md="12"
            v-for="(perm, indexe) in result"
            :key="indexe"
          >
            <h5 class="text-center text-muted">{{ indexe }}</h5>

            <v-row class="alternate-card">
              <v-col
                cols="12"
                sm="3"
                md="3"
                v-for="(item, index) in checks"
                :key="index"
              >
              {{item}}
                <span>
                  <v-checkbox
                    v-model="result[indexe]"
                    :label="item"
                    :value="item"
                  ></v-checkbox>
                </span>
              </v-col>
            </v-row>
          </v-col>
        </v-row>

        <v-divider></v-divider>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue darken-1" text @click="dialog = false"
            >Close</v-btn
          >
          <v-btn type="submit" :disabled="!valid" color="blue darken-1" text
            >Save</v-btn
          >
        </v-card-actions>
      </v-container>
    </v-form>

The script section includes the following logic:


export default {
  props: ["form"],
  data() {
    return {
      valid: false,
      load: false,
      payload: {},
      result: {},
      checks: {
        create: "create",
        edit: "edit",
        delete: "delete",
        show: "show",
      },
    };
  },

  methods: {
    ...mapActions(["editRole"]),
    onSubmit() {
      this.load = true;
       console.log(this.result)
      this.payload.permission = {}
      this.payload.permission = this.result
      if (this.editRole(this.payload)) {
        setTimeout(() => (this.load = false), 1000);
        setTimeout(() => (this.dialog = false), 1300);
      }
    },
    getItem() {
      // Code to fetch item details...
    },
  },
};

At the end of the process, the resulting object will look like this:

{ "package": [ "create", "edit", "delete", "show" ], "category": [ "create", "edit", "delete", "show" ], "product": [ "create", "edit", "delete", "show" ], "assets": [], "users": [], "readers": [] } 

Note that for this specific problem, references to Vuex have been omitted for clarity.

Answer №1

Shoutout to @IVOGELOV for the help! Managed to figure it out, even though it's a bit messy. Made some changes in the code snippet below:

<v-checkbox v-model="result[indexe][index]" :label="item" :value="item" ></v-checkbox>
`checks: {  0: "create", 1: "edit",  2: "delete",  "show",},`

Surprisingly, this adjustment did the trick and I now have an array of checkboxes. Not entirely sure why it worked, but hey, I'll take it! Will definitely work on tidying up my structure moving forward, but for now, this solution will suffice.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring JSON data in React applications

Below is the code I am currently working with: export class Highlights extends React.Component { render() { return ( <div> {JSON.stringify(this.props.highlights_data.data)} </div> ) ...

What is the method for selecting the desired month on a primeng calendar with multiple selection enabled?

I am looking for a solution to make my inline primeNg Calendar display the month of a specific date in the model, and when I remove dates from the model, I want it to show the current month. I have tried using defaultDate={{value}} and minDate={{value}}, a ...

Is it feasible to showcase collections from MongoDB and every individual element from all collections on a single EJS page?

I am currently working on developing a forum for my website using NodeJs, Express, MongoDB, and EJS for HTML rendering. However, I encountered an error message saying: "cannot set headers after they are sent to the client." I am a bit confused about this i ...

Javascript regular expression fails to find a match

Is there a way to match all strings except for the ones containing '1AB'? I attempted it but it returned no matches. var text = "match1ABmatch match2ABmatch match3ABmatch"; var matches = text.match(/match(?!1AB)match/g); console.log(matches[0]+" ...

Navigating the complexities of transferring data between components

I recently started working with Angular 6 and encountered an issue while trying to share data in my project. Below is the code snippets: 1) Component Sidebar: selectedCategory(type:any) { this.loginService.categoryType = type; // need to pass this d ...

Struggling with making JSON.parse() function properly in a Discord Bot

I have a separate JSON file connected like this const Players = require('./Database/Players.json'); and a parser that handles the code client.on('message', message => { if (message.content.toLowerCase() ==='smack activate ...

What is the reason that TypeScript does not automatically infer void & {} as the never type?

When TypeScript's void type is used in combination with other types through intersection, the outcomes vary. type A = void & {} // A becomes void & {} type B = void & '1' // B becomes never type C = void & 1 // C becomes never type D = void ...

Utilizing ng For in a personalized directive to fill a selection menu

I encountered an issue while trying to populate a selected dropdown using ngRepeat inside a custom directive. I came across this example that seemed similar to what I wanted to achieve here. Although it worked for the example, it didn't work for me. ...

Guide to downloading a CSV file directly from a webpage built with vue.js

Delving into the world of vue.js, I find myself pondering over how to incorporate a download link in my webpage for a CSV file stored locally. In my component Template.vue, I have the following structure: <a :href="item.loc" download> {{item.title ...

Assign a value to the input field based on changes made in another input field

I am brand new to the world of JavaScript and currently grappling with setting a value in an input field based on the onchange event of another input field. Here is my code sample for input field 1: <input type='text' onchange='methodTh ...

Should you opt for returning [something] or (nothing) in Javascript with ExpressJS?

Is there a distinct contrast between returning something and returning nothing? Let's take a look at an example: user.save(function(err){ if ( err && err.code !== 11000 ) { console.log(err); console.log(err.code); res.send(&apo ...

Implementing dynamic title rendering based on image in vue.js

This is the code I'm working with, aiming to display slider data. My goal is that if image[0] appears on the slider, it should return title [0]. I'm quite curious about what could be missing in my setup.code-image ...

What is the best way to tally the number of fields in a JSON file based on their values

I'm relatively new to JavaScript and have a question that may seem basic. I've been struggling to find the answer, possibly because I'm not using the correct terminology. My goal is to count the number of "active" fields in a JSON file that ...

The Angular bootstrap datetimepicker doesn't support disabling past dates

Has anyone successfully disabled past dates on an angular bootstrap datetimepicker before? I've tried using the date-disabled attribute, but I can't seem to get it to work. <datetimepicker class="calendar-format" data-ng-model ...

How can you convert Promise.all to a single Promise?

I have successfully implemented two API calls using Promise.all method with no issues. Even though one API call is sufficient to retrieve the results, I decided to stick with Promise.all and it's still working fine. I attempted to replace Promise.al ...

Having trouble setting up react-i18n with hooks and encountering a TypeError: Cannot read property '0' of undefined?

Encountering an error while setting up the react-i18n with hooks: TypeError: Cannot read property '0' of undefined Here's the content of i18n.js: import i18n from 'i18next'; import { initReactI18next } from 'react-i18next/h ...

Attempting to conceal image previews while incorporating pagination in Jquery

I'm working on implementing pagination at the bottom of a gallery page, allowing users to navigate between groups of thumbnail images. On this page, users can click on thumbnails on the left to view corresponding slideshows on the right. HTML <di ...

Having trouble releasing the package on npm platform

I'm facing difficulties in publishing a public package to npm. Despite creating an organization, I'm unable to figure out how to add a new package. Any assistance on this matter would be greatly appreciated. ...

Currently, my goal is to create a functional copy button through the use of JavaScript

I've been attempting to create a basic copy button using JavaScript, but I keep encountering an error. TypeError: null is not an object (evaluating 'myInp.select') Whenever I click the copy button, My code looks like this: <!DOCTYPE htm ...

retrieving the current value of a variable from a jQuery function

I've done my best to keep things simple. Here's the HTML code I've put together: <div id="outsideCounter"><p></p></div> <div id="clickToAdd"><p>Click me</p></div> <div id="in ...