Incorporating interactive checkboxes into a user roster using Vue

I've encountered a common scenario where I need to display data from a REST service in a table using Vue, but I'm struggling to find examples on how to make it work.

When fetching a list of users and showing them in a table, I face an issue with adding a "checked" attribute dynamically. Here's a simplified version:

<tr v-for="guser in filteredUsers" class="group_user">
    <td><input type="checkbox" v-bind="guser.checked"></td><td>{{guser.username}</td>
</tr>

The problem arises from the fact that the "checked" attribute is not part of the user object retrieved from the backend. Therefore, I need to add it on the client side after fetching the data. This approach makes sense since the backend doesn't need to know about this frontend functionality.

However, I'm facing difficulties with the binding of v-bind="guser.checked". It seems that any attribute bound to a form control needs to be predefined when declaring the objects. But how can I achieve this for a dynamic list of N objects received from the server?

If anyone has advice or insights on this matter, I would greatly appreciate it. Thank you!

Answer №1

Ensure to include the checked property in your user objects once they are fetched using AJAX.

console.clear()

// simulated data from the server
const users = [
  {id: 1, username: "Bob"},
  {id: 1, username: "Mary"},
]

new Vue({
  el: "#app",
  data:{
    users:[]
  },
  computed:{
    filteredUsers(){
      // simulate filtered users
      return this.users
    }
  },
  methods:{
    getUsers(){
      // simulate an ajax call with setTimeout
      setTimeout(() => {
        // add a checked property to the retrieved user objects and assign the result to users array
        this.users = users.map(u => Object.assign({}, u, {checked: false}))
      }, 250)
    }
  },
  created(){
    this.getUsers()
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
  <table>
    <tr v-for="guser in filteredUsers" class="group_user">
      <td><input type="checkbox"v-model="guser.checked"></td>
      <td>{{guser.username}}</td>
    </tr>
  </table>
  {{users}}
</div>

If it doesn't seem to work initially, it might be due to Vue's inability to detect dynamically added properties to an object after being added to Vue. Another approach would be utilizing the $set method for adding properties (instead of Object.assign as demonstrated).

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

Setting variables in AngularJS services without encountering JavaScript undefined errors

After developing an AngularJS module, I attempted to link a service and use it to share variables across the application. While most things are functioning properly, I encountered an issue when trying to set submenu[1] to an object. The error message sta ...

Comparing two popular JavaScript libraries for 2D rendering: pixie.js vs three.js

When it comes to rendering 2D graphics using WebGL, there are a limited number of JavaScript libraries available. After some research, I have discovered that the two most popular choices are three.js and pixi.js. Both of these libraries offer the flexibili ...

Utilize Mongoose aggregation to dive into a nested document, retrieve a count, and add a fresh value to the final

I have a collection of users and posts with embedded documents for comments and replies: users { _id:34 name:"dimer" } Posts { _id:"1234", body:"hello! I love mongodb, but it's hard", likes:["34"], co ...

Why is ReactCSSTransitionGroup creating numerous components when I am anticipating just one?

While experimenting with ReactCSSTransitionGroup for animations, I encountered a peculiar situation that doesn't quite add up in my understanding. In the scenario below, every time I click on <div className="HeartControl">, it updates the heigh ...

Retrieving data via AJAX from an SD card

I am using the Atmel SAM4E-EK microcontroller as a server to host a webpage and send data over HTTP protocol. I am currently facing an issue with the download function while trying to download a file from my sd_card, which will not be larger than 512MB. s ...

Display temporary image if image is not located

I attempted to utilize the onerror attribute to display a placeholder image when the desired image is not found in the folder. The image path is dynamically generated from the backend. The code snippet below shows how I implemented this: <img class=&quo ...

Tips for sorting through an array of objects in JavaScript?

I'm currently working on filtering my array within an Angular 4 component. The array includes a property that is also an array: export const data = [ { "number": "1", "lines": [ "aaaaabbbb bbbbb ccccc ddddd", "aaaaabbbb bbbbb cc ...

Is there a way to conceal the faces of a mesh in three.js?

Is it possible to make certain parts of a mesh invisible during runtime by changing attributes of single faces? The mesh is using only one material. Visual Example of the question: Picture a mesh with 20 vertices where each quad is made up of four vertice ...

Tips for maintaining an active class on parent nav items in NextJS when navigating dynamic routes

In my nextjs-application, I've implemented a Navbar showcasing several navitems: Navbar.tsx: const Navbar = ({ navitems }) => { return ( <div> {navitems?.map((navitem, idx) => ( <NavItem key={idx} navitem={nav ...

The left and right arrows maintain their visibility even when they are outside of the image

I am a beginner in the world of web development and I am trying to implement left and right navigation for images using arrows. My goal is to have the arrows fade in when the mouse hovers over the image and fade out when it's moved away. However, I am ...

What could be causing the issue of dynamic values not getting submitted from a form in NextJS?

In my current project, I am utilizing React within a NextJS framework. When I manually input values into form fields and submit the form, I am able to access all the values in the component function. However, when I populate a form field dynamically usin ...

What could be causing the data to be displaying as undefined when using AJAX

My issue involves making an ajax call and passing an array with data. However, when I attempt to debug the code in the console, it shows that the data is undefined. What could be causing this? ...

Sorting a Vue.js checkbox in the header of a data table

I'm currently facing an issue with a project I'm handling. The data in question is stored in a v data table, where the header data is retrieved from an external API. Inside this table, there are checkboxes for users to select specific businesses ...

Instructions for populating a DataTable with JSON data while allowing for editing of rows

Hey there, looking for some expert advice, I've been experimenting with the datatable plugin and I'm curious if it's feasible to populate a table with row editing actions using ajax? This is the code snippet I currently have. It successfull ...

Unable to process JSON array

One issue I'm facing is with an 'onload' handler for my web page. The javascript function 'handleLoad()' that it calls has suddenly stopped working, specifically not being invoked after attempting to pass the output of json_encode ...

Tips for integrating external JavaScript libraries and stylesheets into a widget

I am currently working on developing a custom Javascript widget that requires users to insert specific lines of code into their web pages. This code will then dynamically add an externally hosted javascript file, allowing me to inject HTML content onto the ...

javascript href clears Internet Explorer webpage

I noticed a strange issue with my HTML page. In Internet Explorer, when I click on the link, it displays the return value on a blank page. However, in Chrome, it simply executes the function without affecting the page appearance. Is there a way to make I ...

Unable to modify the logo images in React

I'm struggling to figure out how to make my images (favorite.svg and favorite-white.sgv) change every time the button is clicked in React. I've tried various solutions but it's proving to be quite challenging. When the button is clicked, I ...

Implement dynamic routing in React based on a specific condition

Working on implementing a routing logic for my react application. Here's the scenario: I have 2 pages and 2 roles (user and reviewer) in my app and here's what I want to achieve: If a user accesses the app, they should be redirected to "/ ...

Explore the capabilities of Vue.js by creating multiple JavaScript classes within your application

<div class="container" :class="{ qwerty: !open }" :class="lower? 'left' : 'right'"> Hey there, I've noticed that Vue seems to only allow me to add one class with conditions, as shown in the exam ...