Utilizing v-model for dynamic binding within a v-for iteration

I'm currently working on binding v-model dynamically to an object property within an array of objects. I am unsure about how to accomplish this task. The objective is to choose a user using the Select HTML tag and then display the list of that user's permissions (from the array of objects) in order to toggle between true/false using checkboxes. These changes should be saved to the corresponding object property inside the array of objects.

Template:

<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="(perm, id) in users[getUserIndex].perms">
      <span>{{ perm.status }}</span>
      <input type="checkbox" v-model="">
    </li>
  </ul>
</div>

script

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 }
    }
  },
})

I am providing the link to this JSFiddle as I find it challenging to explain in text.

https://jsfiddle.net/sgtmadcap/49bjwahs/141/

I am seeking guidance on dynamically binding v-model to each users[someindex].perms.perm property for modification. My ultimate goal is to update this array with all changes to a Firebase database. Thank you for any assistance provided! I understand that this might be basic, but I appreciate any help offered. P.S. Apologies for any English mistakes.

Answer №1

If you simply use

<input type="checkbox" v-model="perm.perm">
in your scenario, it should work just fine.

However, I recommend doing some refactoring and renaming because the usage of perm.perm indicates that your current data structure and naming may not be very intuitive.

One suggestion is to create a computed property to fetch the userPermissions instead of directly accessing the array index in the template.
It might also help to rename your object properties as something like permissions and isAllowed for better clarity.

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

In your template, consider implementing:

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

Answer №2

This should function as intended.

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>

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

Having issues with Json stringification and serializing arrays

Having an issue with Json when using serializeArray. An example of my HTML form: <form action="" method="post" name="myForm"> ID: <input type="text" name="id" /><br/> State (XX): <input type="text" name="state" /><br/> <p ...

Transforming the String Values in an Array to Capitalize the First Letter of Each Word Using VueJS

After receiving an array of objects from an API call: "data": [ { "heading_one_of_the_table": 14, "total": 8 }, { "heading_one_of_the_table": 1, "total": 7 }, { "heading_one_of_the_table": 6, "total": 7 } ] I want to ...

Is there a way to execute a jar file using JavaScript?

Hello, I'm new to this and still learning. I have a jar file that takes one parameter and returns a JSON with the result. Could someone please advise me on how to run my jar using JavaScript? I've attempted the following code but it's not wo ...

It is imperative that the 'Access-Control-Allow-Origin' header value in the response is not set to '*' when the request's credentials mode is 'include'

I am currently working on establishing a connection using socket.io between Angular and a Node.js Server Within Angular, I have set up a new socket by importing socket.io-client and connecting it as follows: import * as io from 'socket.io-client& ...

Guide on implementing the recently established attribute ID using jQuery

In my code snippet, I am assigning a new id to a button. Here is the code: $("#update").click(function(){ $("#update").attr('id', 'cancel'); }); After changing the id, I want to make it functional again in jQuery by reverting it b ...

Angular reactive form encountered an issue with an incorrect date being passed

Currently, I am utilizing the PrimeNg calendar module to select a date. Here is the code snippet: <p-calendar formControlName="valid_till" [dateFormat]="'mm/dd/yy'"></p-calendar> Upon selecting a date like 31st J ...

Learn how to execute the dialog content destroy function once a Vuetify dialog is closed

I'm a beginner with Vuetify and I have noticed that, currently, there is no built-in method to completely remove the body of a dialog when it's closed. Does anyone have a workaround for this issue? When dealing with forms, we can reset field val ...

Trouble with displaying ChartsJS Legend in Angular11

Despite thoroughly researching various documentation and Stack Overflow posts on the topic, I'm still encountering an odd issue. The problem is that the Legend for ChartsJS (the regular JavaScript library, not the Angular-specific one) isn't appe ...

Utilizing the dynamic pairing of Three.js and CSS3 to bring life to animated 3D objects

I am currently working on a project that involves creating 3D Lego elements and assembling them into a figure using animation. I have successfully modeled the elements in Blender and exported them as .obj/mlt files without any issues. However, when it come ...

The functionality to redirect in Wordpress Contact Form 7 based on the value of a radio button selection does

For the past 5 hours, I have been diving deep into Contact Form 7 redirects that are based on values. Despite my efforts, I am unable to figure out why my code isn't functioning properly. Is there anyone who can spot the issue? Contact Form Radio But ...

Encountering an issue with finding the module `scheduler/tracing` in React Native

Encountering an error during the react-native run-android process: Error: Unable to resolve module `scheduler/tracing` from `/Users/miftahali/projects/react/appscustomec/node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js`: Module ...

Is there a specific interface or class in PHP SPL that allows for controlling the behavior when casting to an array?

By incorporating the Iterator, ArrayAccess, and Countable built-in interfaces, we are able to manage what occurs within an object when utilized in foreach loops or if a property is accessed as if it were an array index ($object['id']). For insta ...

Unable to send post parameters to Yii2 controller using an XHR request

Within the context of my project, I am making an xhr request to a yii2 controller. Here is how the request is structured in my view: var xhr = new XMLHttpRequest(); xhr.open('POST', '$urlToController', true); xhr.setRequestHeader("Co ...

Transitioning from utilizing Jquery for post requests to implementing modern Promises

Currently, I am involved in a web application project that utilizes Flask and Python on the back-end with JavaScript on the front-end. I have been contemplating leveraging more modern styles like ES6/7 features such as Promises. In my development process, ...

Contrasting $interval and setInterval functions in AngularJs

I am trying to grasp the distinction between $interval and setInterval. I have come up with this test: Dashboard.prototype.updateTotalAppointments = function(){ //console.log(); this.appointmentsCount = this.appointmentsCount +1; console.log(this.appointm ...

Establishing Accessor and Mutator Methods

The variables startStopA... and InitialValueA... that were originally in the component TableFields.vue need to be relocated to the store file index.js. However, upon moving them to the store, an error appears stating that setters are not set. I have extens ...

Is it possible to pass an AngularJS ng-form object as a parameter in ng-if?

When I try to preview, the save button in my preview mode remains enabled. You can view the code snippet here: http://plnkr.co/edit/I3n29LHP2Yotiw8vkW0i I believe this issue arises because the form object (testAddForm) is not accessible within the ng-if s ...

Assign a class to each offspring of a slot

I am currently in the process of setting up a component with a slot that, upon rendering, adds a specific class to each child within that slot. To simplify: <template> <div> <slot name="footerItems"></slot> </div> ...

Guide to reference points, current one is constantly nonexistent

As I work on hosting multiple dynamic pages, each with its own function to call at a specific time, I encounter an issue where the current ref is always null. This poses a challenge when trying to access the reference for each page. export default class Qu ...

What is the best way to modify a single item within a v-for loop in Vue.js 3?

I am attempting to achieve the following: <tr v-for="item in items" :key='item'> <td v-for="field in fields" :key='field'> {{ item[field.toLowerCase()] }} </td> </tr> It seems that ...