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

What is the best way to obtain a user's ID on the server side?

I'm currently working on a node.js application using express and I am in need of retrieving the user ID. I would like to have something similar to "req.userID" so that I can use it in the following way: var counter=0; var user = new Array(); router.g ...

Creating linear overlays in Tailwind CSS can be achieved by utilizing the `bg-gradient

Is there a way to add a linear background like this using Tailwind CSS without configuring it in tailwind.config.js? The image will be fetched from the backend, so I need the linear effect on the image from bottom to top with a soft background. Here are ...

Why is it unnecessary to include a callback when using a setState function from useState as an argument in useEffect?

While working with a function from my component in the useEffect arguments, it is recommended to write a callBack so that it is memorized and used as a dependency of the useEffect. Without this, there is a warning. However, when using the setState of use ...

Displaying geoJSON data from a variable instead of a file is a feature implemented by

Let's say I have a geoJSON data stored in a variable or parsed as an object: // GeoJSON stored as an object var segment = segment; // GeoJSON saved as a JSON string var json = JSON.stringify(segment); Now, the challenge is to display this geoJSON o ...

What is the reason behind the significant 80% reduction in PNG files by grunt-contrib-imagemin compared to the minimal reduction of less than 0.1%

Just getting started with Grunt here. Recently, I've been experimenting with grunt-contrib-imagemin. When it comes to compressing PNG files, it does an impressive job. It typically reduces the size by around 80%. However, I'm finding that the ...

What is the most effective method to update the interface following the addition of item data to the database?

How can Vue.js refresh the interface after adding a new strip of data to the backend database? When an item is added to the database, there are two options for refreshing the interface: Refresh the list API to retrieve the updated page data. Add the new ...

What is the best way to interpret this supposedly JSON structure?

I have a large data file in the format below, which is the response from an API call to one of Twitter's APIs. I need to extract the "followers_count" field value from it. Typically, I would use jq with the command: cat | jq -r '.followers_count ...

Is there a way to ensure that the line numbers displayed for JavaScript errors in Chrome are accurate?

I suspect either my webpack configuration or my npm run dev script are causing the issue, but I'm unsure of what exactly is going wrong. While running my application in development mode, I encounter error messages like: Uncaught TypeError: this.props ...

What is the best way to delete HTML classes that were generated by a function?

Currently, I'm immersed in the Etch A Sketch project as part of my journey through The Odin Project. Using DOM manipulation, I successfully created a grid and displayed it on the screen. Now, my aim is to allow users to resize the grid by removing the ...

Q: How can I retrieve an array of arrays containing JSON object values from an array of objects?

When given a JSON input structured like this: [ { "k1": "o1k1", "k2": "o1k2", "k_opt1": "o1k_xxx" }, { "k1": "o2k1", "k2": "o2k2", ...

Exploring the functionality of className using materialUI

Attempting to test whether my component has a specific class is proving challenging. This difficulty stems from the fact that the class is generated using MaterialUI. For instance, I am looking for a class named spinningIconCenter, but in reality, it appea ...

The feature for sending posts in Angular.js appears to be malfunctioning

I have developed a rest-API for adding todos in a MongoDB database. When I use Postman with the setup below, I can successfully save instances: http://localhost:3000/api/addtodo x-www-form-urlencoded with values text="Test", completed: "false". However, ...

Clicking on the React Bootstrap Checkbox within the Nav component does not trigger a rerender of the NavItem component

Encountering an unusual issue while using a Nav and NavItem with a Checkbox from React Bootstrap. What I've noticed is that when clicking directly on the checkbox instead of the NavItem button, the checkbox does not re-render correctly even though my ...

Exploring Pyspark: Implementing the best approach to handle nested arrays in JSON data as "column-row" or "key-value" format

I have a unique json file structured similarly to the example below. My goal is to extract the information and display it in a table format with all the attributes of the individual. { "person":[ [ "name", "Jane ...

Utilizing props for toggling the navigation list, incorporating nested arrays or objects

My issue involves two components that are loading data. I want the links to be output like this: group1 linka linkb However, they are currently displaying like this: group1 linka group1 linkb I believe the problem lies in how I am handling the ...

Navigation guard error: Caught in an infinite redirect loop

I have set up a new vue3 router and configured different routes: const routes = [ { path: "/", name: "home", component: HomeView, }, { path: "/about", name: "about", component: () => ...

Tap to navigate to queued sections on click

Greetings, community members! Despite my extensive research, I have been unable to find a solution to my query. Just a heads up - I am a novice when it comes to javascript and jQuery. My question pertains to incorporating two image buttons that, upon cli ...

What is the best way to display data retrieved from a GET request in Angular?

Spending too much time on a development issue is causing me frustration. After extensive research, I find myself stuck at this point. The problem lies in making a GET request from a service which is called by a controller. Below is the code for the servi ...

What is the best way to enlarge text size with jquery?

I am attempting to: $('a[data-text="size-bigger"]').click(function () { a=$('span'); b=$('span').css('font-size'); a.css('font-size', b+1); } ); Initially, I ha ...

What is the best method for applying an active class to a particular element?

I have the following methods: methods: { replyBox: function(event){ event.preventDefault(); this.isActive = !this.isActive; ); }, In my view, I have this: <div class="comment_list" v-for="comme ...