Use Vuejs to add the details of the selected item to an array and then dynamically update the array when items are checked or unchecked

My products json contains various details similar to the examples below.

products.json

products: [
        {
            "id": "6",
            "name": "Cake-WhiteForest",
            "manufacturer": "Cake Cafe",
            "category": "WhiteForest",
            "color": "White",
            "available": true,
            "address": "16th Lane",
            "quantity": 8,
            "description": "milk chocolate wafer",
            "price": 12,
            "delivery": "small"
        },
        {
            "id": "10",
            "name": "Donuts-Choco bun",
            "manufacturer": "Donut House",
            "category": "Choco bun",
            "color": "chocolate",
            "available": true,
            "address": "13th Avenue",
            "quantity": 14,
            "description": "Donuts with dark chocolate",
            "price": 13,
            "delivery": "minibox"
        }
       ]

I am presenting these product names in a list format with checkboxes, like this:

CheckBox1  Cake-WhiteForest
CheckBox2  Donuts-Choco bun

methods: (checkbox change event)

check(e) {
    if (e.target.checked) {
      let selectedProduct = this.products.find(item => item.id === e.target.value)
      this.getCheckedProducts.push(selectedProduct)
    }
}
    

Component Code for this

<li
                v-for="product in products"
                :key="product.id">
                <span>
                  <input type="checkbox"
                         :id="product.id"
                         :value="product.id"
                         v-model="checkedProducts"
                         @change="check($event)"/>
                  <span class="doc_input">
                    <i class="el-icon-folder" aria-hidden="true"></i>
                  </span>
                  <span class="product__name">
                    {{product.name}}
                  </span>
                </span>
              </li>

The issue arises when I select both items from the list. Although it correctly adds them to the 'getCheckedProducts' array, unchecking one of the checkboxes does not update the array. Both items remain selected. How can I manage the checkbox state?

The v-model log provides prototype details. How should v-model be utilized in this case where an array of objects is being passed?

Answer №1

It is recommended to avoid manually creating the function getCheckedProducts. Utilize the existing variable checkedFiles, which already contains the IDs of the checked products. By implementing a computed property called checkedProducts that is based on checkedFiles, your product list will automatically update whenever a checkbox is checked or unchecked. This is because the v-model will be updated automatically, triggering an update in all computed properties dependent on it.

computed: {
  checkedProducts() {
    // Map ids to their corresponding products
    return this.checkedFiles.map(
      id => {
        // Assumption: All ids in checkedFiles actually have a product in the products array
        return this.products.find(product => product.id === id);
      }
    );
  }
}

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

Error encountered: The EVM has reverted the transaction

After successfully deploying this basic smart contract using Remix, I encountered an issue when trying to interact with it through web3.js in my upcoming app. I used the evm version: paris for deployment and everything worked smoothly on Remix IDE. Here i ...

Error encountered while attempting to import the mongoose npm module into a React application

I'm encountering an issue in my React project where I am trying to include an npm module within a component. Here's an example: var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test', {useNewUrlParser ...

Modifying button appearance upon clicking using JavaScript

JavaScript: const buttons = document.getElementsByClassName("togglebtn"); for (let i = 0; i < buttons.length; i++) { buttons[i].onclick = function () { this.classList.toggle("active"); } } html: <md-butt ...

Error encountered: In ExtJS 4, a type error is being displayed stating that the URL is undefined

I have a scenario where I am creating a combo box using ExtJS 4 within an editable grid, and instead of using an ExtJS proxy, I am making an external AJAX call to populate it. The reason behind this approach is that I am using the same call to load other c ...

How can I create a button that prints the page content and then sends it to the backend using JavaScript for submission?

Is there a way to print content from a page and then submit form data to make changes to a backed database using just one button? I've attempted to include the print action within an on-click function, but it does not submit the form after printing. ...

"Creating a 2D array in Java and outputting it

I need assistance with printing the array I've created below in a specific format. NOTE: the code provided is only a section of my entire code, so any advice or comments preceding this portion are unnecessary. String [][]myList = {{"cat", & ...

The disappearance of HTML DOM nodes event

When I relocate certain DOM nodes from one context to another, some of the child nodes end up losing their event listeners. HTML <div><lots of nested nodes .../><div> <div> <div> <div#newNode></div> < ...

How can I incorporate popups in React using mapbox-gl?

Currently utilizing mapbox-gl within React, everything seems to be functioning properly except for the integration of mapbox-gl's Popups. I have the function let Popup, but I am uncertain about how to incorporate it. renderMap() { if (this.props. ...

What is the best method to eliminate elements from one array based on the presence of an element in another array in Python

I need help removing all the nans from D1 or B1, as well as the same i-th elements from all the arrays (e.g. 2nd element of each array, and so on). import numpy as np V1 = [ 7.98083 16.5216 18.4423 15.644 15.539 15.89 12.092 19.4274 14.953 15 ...

Tips for integrating Tailwind CSS into Create React App using React

I recently started using tailwindcss with my react app. I tried to follow the guide from tailwindcss but encountered various issues and bugs along the way. If anyone has advice on how to successfully start a project using tailwind and react, I would apprec ...

Extract data from nested JSON and populate a list with corresponding values

<ul> <li><a href="" class="edit">a unique item in the list</a></li> <li><a href="" class="edit">another unique item in the list</a></li> <li><a href="" class="edit">yet another unique ...

Is there a way to eliminate the feature that rearranges characters in reverse order?

Is there a way to modify this code to only replace vowels with "er" instead of reversing the order of characters? I'm hoping to remove the function that reverses the character order. If you want to take a look at the code, it's available on Past ...

Calculate the total count of responses within the JSON data returned

Hello all, I need some guidance on calculating the total number of responses in a JSON response that adhere to a specific rule using JavaScript. Here is the JSON response that I am discussing: [ { "InvoiceNumber":"INV0319", "InvoiceOrd ...

What is the process for accessing getters and mutations within a Vuex module?

As I make the transition to using Vuex instead of my custom store object, I have come across some challenges with understanding the documentation in comparison to other resources within the Vue.js community. For example, if I have a Vuex module named &apos ...

The backend API seems to be facing issues with loading images fully in Vuejs

Scenario: In my WebApp (frontend: Vue3, backend: node.js + express), there is a single vue component with a button. Clicking this button triggers a script in the backend to download an image and save it locally. The goal is to render this image on the Vue ...

the current situation is that the nowjs initialize function is not working as

var express = require('express'); var app = express(); var nowjs = require('now'); app.get('/', function(req, res) { res.send('index'); }); var server = app.listen(4000); /* Setting up now.js to broadcast functio ...

The AngularJS view refuses to load when accessed from the browser, although the identical code successfully loads the view on

Here is the link to my plunker where the view loads as expected on Plunker's website. Check out My First Angular Single Page Application However, after downloading the files from Plunker and unzipping them on my local machine, the view does not load ...

Retrieving an array value by key from user input in HTML

<input type='number' name="productId" id="productId" value="5"> <input type="number" name="quantity[]" id="quantity"> In order to retrieve the quantity value, I utilized var values = $("input[name='quantity[]']") ...

What is the best method to display the content in the second response for ajax's authorization and dealing with cors?

I have successfully implemented basic authorization and enabled CORS on my VPS. Check the CORS preflight request using cURL: HTTP/1.1 200 OK Date: Sat, 15 Sep 2018 08:07:37 GMT Server: Apache/2.4.6 (CentOS) Access-Control-Allow-Origin: http://127.0.0 ...

Mastering the art of Promises and handling errors

I've been tasked with developing a WebApp using Angular, but I'm facing a challenge as the project involves Typescript and asynchronous programming, which are new to me. The prototype already exists, and it includes a handshake process that consi ...