Tracking changes in values from an array of objects in Vue.js can be achieved by implementing a method that

Within my code, there is an array called addRows that holds a collection of objects.

These objects are dynamically added when the user clicks on a specific button.

Once added, these objects are then pushed into the addRows array for the user to fill in.

Each object within this array contains various input values like price and quantity.

The challenge I am facing is updating the price when the quantity changes. The issue arises when the new value overlaps with existing values, causing the returned item to be empty.

This occurs because the new value has already been added to the old values array.

In the image displayed, the third value is the same as the first, resulting in the array returning an empty value for the third item.

I have attempted using foreach, for loops, and maps, but unfortunately, I continue to encounter the same problem.

computed: {
    originalDistValue(a , b) {
        return this.addRows.map(i => {
            return i.dist
        })
    }
}, // close computed

watch: {
    originalDistValue(a , b) {
        let newVal = a.filter( obj => {
            return b.indexOf(obj) == -1;
        })

        let element = this.addRows.filter( i => {
            return i.dist == newVal;
        })

        deep: true 
        console.log(newVal)

        for(let i in element) {
            element[i].cit = 1;
        }
    }
}

Answer №1

  • To start, create a child component for every row
  • Send each row to the component
  • Manage the single object within the component instead of handling an array of objects in the parent

Take a look at this example:

    Vue.component('child', {
  props: {
    value: { type: Object, default: () => ({}) }
  },
  data: function() {
    return {
      selfValue: null
    }
  },
  watch: {
    value: {
      handler(value) {
        this.selfValue = value
      },
      immediate: true,
      deep: true
    },
    selfVaue: {
      handler(value) {
        // you can also validate value then emit it
        this.$emit('input', value)
      },
      deep: true
    },
    'selfValue.quantity'() {
      this.selfValue.price = 0
    }
  },
  template: `
     <div class="d-flex justify-content-between">
        <label>
          Title:
          <input type="text" v-model="selfValue.title" class="form-control" />
        </label>
        <label>
          Quantity:
          <select v-model="selfValue.quantity" class="form-control">
            <option value="A">A</option>
            <option value="B">B</option>
          </select>
        </label>
        <label>
          Price:
          <input type="tel" v-model="selfValue.price" class="form-control" />
        </label>
     </div>
    ` }) newVue({ el: '#app', data: { rows: [] }, methods: { add() { this.rows.push({ title: '', quantity: '', price: 0 }) } } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div id="app" class="container">
  <h2 class="mb-3">Rows:</h2>

  <div v-for="row,i in rows">
    <child v-model="row"></child>
    <hr class="mt-1 mb-1" />
  </div>
  
  <button @click="add" class="mb-3">
    ADD
  </button>
  
  <pre>{{ rows }}</pre>
  
</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

Adjusting the z-axis rotation in a three.js animated scene

Is there a way to add a function that changes the Z rotation value of the teapot from within the updateTeapot function? I came across this helpful answer on Three.js camera tilt up or down and keep horizon level. However, I am unsure how to integrate a z ...

A guide to retrieving all image URLs when a checkbox is selected using Javascript

My goal is to extract only image URLs from the concatenated values of price and picture URL. However, when I check different images using checkboxes, it always displays the URL of the first selected image. When I try to split the value, all the prices and ...

When using NodeJS, having multiple 'if' statements may result in conflicting headers being returned,

Introduction to Promises. Encountering challenges in NodeJS due to the utilization of multiple if-statements and return-statements. Considering leveraging Promise as a potential solution. This snippet showcases an example: const express = require(' ...

Divide a string into separate numbers using JavaScript

This snippet of code is designed to search the table #operations for all instances of <td> elements with the dynamic class ".fuel "+ACID: let k = 0; let ac_fuel = 0; parsed.data.forEach(arrayWithinData => { let ACID = parsed.data[k][0]; ...

Filter through the array using the cast method

Trying to implement this: let selections = list.filter(obj => obj.type === "myType"); An issue arises with the filter function displaying an error message which states 'filter' does not exist on type 'NodeType' I attempted to ...

What is the correct way to promise-ify a request?

The enchanting power of Bluebird promises meets the chaotic nature of request, a function masquerading as an object with methods. In this straightforward scenario, I find myself with a request instance equipped with cookies via a cookie jar (bypassing req ...

Setting up HMR for a Vue.js app can be a bit tricky, especially when trying to run it locally

1. The Caddy version I am using (caddy -version): v2.0.0-beta.13 h1:QL0JAepFvLVtOatABqniuDRQ4HmtvWuuSWZW24qVVtk= 2. How I execute Caddy: a. Environment details: I have the caddy server static binary running on macOS Mojave - 10.14.6, and added the bina ...

Seamless mathematical computations while navigating through Javascript

I have created a basic JavaScript calculator that works efficiently. However, after obtaining the result by pressing the "=" button, I would like the returned result to be saved for future use. The "=" button should be capable of being clicked again to ret ...

Error: The command "vue" is not recognized

I am encountering an issue while trying to set up vue-cli using npm. Each time I check the version, I receive the error message -bash : vue: command not found. Despite my efforts which include uninstalling and reinstalling, as well as referring to resourc ...

PHP data is not displayed by Ajax

I seem to be encountering a bit of trouble. I am attempting to utilize ajax to retrieve data from a PHP server, which in turn fetches it from a MySQL database, and then display it within a specific HTML tag location. However, for some unknown reason, nothi ...

Angular utilizes ZoneAwarePromise rather than a plain String output

I expected the giver code to return a string, but it is returning ZoneAwarePromise. Within the service: getCoveredPeriod() { let loanDetails = this.getLoanDetails().toPromise(); loanDetails.then((res: any) => { const coveredPeriodStart ...

What is the best approach for retrieving Google API responses - accessing them directly from the frontend or routing through the backend first?

Currently, I am in search of the optimal location to make Google API requests. Given that Google Maps is utilized in the front end, we have the option to directly call the distance API service from there. However, we also have the choice to access these se ...

During initialization, React/Redux reducer produced an undefined value

Recently, I started working on my debut React/Redux project. Initially, everything was smooth sailing until I decided to implement a new reducer. The process seemed straightforward, but upon loading the page, an error popped up stating "Reducer X returned ...

Leveraging google transliteration within a Flex environment

Here is an illustration of how the Google transliteration feature can be utilized in specific HTML textboxes. I am looking to incorporate this same functionality for a Flex application. Is there a method through which this can be achieved? <html> ...

issue concerning slide functionality and ajax integration

I'm facing an issue with the structure of my HTML. Here is the setup I have: <div id ="slide1"> <form method="post" id="customForm" action=""> //my content - name, email, mypassword, pass2 </for ...

KnockoutJS is not recognizing containerless if binding functionality

I was recently faced with the task of displaying a specific property only if it is defined. If the property is not defined, I needed to show a DIV element containing some instructions. Despite my efforts using $root and the bind property, I couldn't ...

What's the best way to execute multiple actions within a single gulp task?

Is there a way to execute multiple actions within one gulp task? I have tried using event-stream's merge feature following the example in How to perform multiple gulp commands in one task, but it doesn't work properly when combined with the del p ...

How can I use jQuery to either display or hide the "#" value in a URL?

I have a question that I need help with. Let's say I have the following links: <a href="#test1"> Test </a> <a href="#test2"> Test 2 </a> When I click on Test, the URL will change to something like siteurl/#test1. However, whe ...

Express string declaration in a single TypeScript line

const restrictString = (str: string): string => str.match(/[ab]/g)?.join('') || '' Is there a way to restrict a string to only contain the characters 'a' and 'b' in a one-liner function? I am aware that this can ...

Is it possible to execute PHP without using Ajax when clicking on a Font Awesome icon?

So, besides using Ajax, is there another solution to achieve the same result? Can a font-awesome icon be turned into a button without Ajax? In case you're unfamiliar with what I mean by a font-awesome icon, here's an example: <i id="like1" on ...