Vuejs Dynamic input binding and computed function is throwing an error

I'm struggling with dynamically setting the v-model for inputs based on dropdown selection. Currently, I am using dummy data and need help to fetch actual data from the backend.

Take a look at the screenshot.

For example, each row has three input boxes: numerator, denominator, and computed value. I have assigned v-models like form['num_' + idx], form['den_' + idx], form['comp_' + idx] respectively. These are part of a form object in the data (state).

The issue arises when I try to bind the computed value input box using a computed property as I cannot pass arguments and receive an error stating that computedValue is not a function.

I've attempted placing the computedValue function in the methods section and added a button next to each computed input box. However, what I really need is for the computed value input box to automatically calculate and display the result whenever the numerator or denominator values change.

Unfortunately, the computed input box does not always show the correct value. Sometimes it only updates when changing data in other rows.

<template>
  <div>
    <select v-model="service">
      <option disabled value="">Please select one</option>
      <option>Order to cash</option>
    </select>
    <select @change="changeAccountEvent($event)" >
      <option disabled value="">Please select one</option>
      <option>Nissan</option>
      <option>Ford</option>
    </select>

    <div>
      <ul>
        <li v-for="(d,idx) in data" :key="d.metric">
          <div class="flex px-4 py-2">
            <div class="w-1/4">{{d.metric}}</div>
            <div class="w-1/4 mr-2">
              <input v-model="form['num_' + idx]" type="number">
            </div>
            <div class="w-1/4 mr-2">
              <input v-model="form['den_' + idx]" type="number">
            </div>
            <input v-model="form['comp_' + idx]" type="number" >
            <button
              @click="computedValue(form['num_' + idx], form['den_' + idx], idx, d.formula)">get value
            </button>
            <!-- :value="computedValue(form['num_' + idx], form['den_' + idx]) -->
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      service: '',
      account: '',
      data: null,
      form: {

      },
    };
  },
  methods: {
    computedValue(a, b, c, d) {
      console.log('a -> ', a, 'b -> ', b, 'c -> ', c, 'd -> ', d);
      this.form[`comp_${c}`] = parseFloat(a) / parseFloat(b);
      console.log(this.form);
    },
    changeAccountEvent(event) {
      if (this.service !== '') {
        this.account = event.target.value;

        if (this.account === 'Ford') {
          const fordData = [
            { metric: 'Days Sales Outstanding', formula: '/' },
            { metric: 'Past due percent', formula: '/' },
            { metric: 'Days', formula: '/' },
            { metric: 'percent', formula: '/' },
          ];

          this.data = fordData;
        }

        if (this.account === 'Nissan') {
          const nisData = [
            { metric: 'Days Sales Outstanding', formula: '/' },
            { metric: 'Past due percent', formula: '/' },
          ];
          this.data = nisData;
        }
      } else {
        // event.target.value = '';
        alert('please select service line');
      }
    },
  },
};
</script>

Your guidance will be highly appreciated.

Cheers, Meet

Answer №1

To maintain reactivity in object updates, it is important to utilize Vue.set instead of directly using index [].

For instance:

this.data[`item_${i}`] = parseFloat(x) + parseFloat(y);

Consider using:

Vue.set(this.data, `item_${i}`, parseFloat(x) + parseFloat(y));

Answer №2

It's important to utilize reactive properties to ensure that your vm is informed of any changes to a property and updated reactively.

The variables form['num_' + idx], form['den_' + idx], and form['comp_' + idx] do not exhibit reactivity because they have not been explicitly declared within the object returned from the data() method in the script block.

To address this issue, you can employ Vue.set/Vue.prototype.$set, also known as this.$set, to dynamically establish reactive properties like so:

this.$set(this.form, 'num_' + idx, value)

For more information on reactivity, refer to Reactivity in Depth - Vue.js

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

Executing a function on a dropdown menu in AngularJS

Currently facing an intriguing scenario that is causing me some confusion. This question is specifically for those well-versed in Angular UI Grid, but all responses are welcome. The situation revolves around a UI Grid with a dropdown functionality impleme ...

What could be causing my default prop to not be transmitted to the child component in vuejs2?

Having trouble passing a default value to my Leaflet map child component before fetching the desired data from an API endpoint. I tried using country coordinates like latitude and longitude, but it's not working as expected. This is how I attempted t ...

Sort the Vue.js array by year and search for items by tag

In my VueJS project, I am working with data fetched from an API using axios. The data consists of projects with various properties such as year, location, and tags like house or park. I have implemented a filtering system to sort the projects based on a sp ...

Explain the purpose of the describe() function in Mocha testing framework

Exploring Mocha has been a goal of mine and I recently came across this example in the documentation: var assert = require("assert") describe('Array', function(){ describe('#indexOf()', function(){ it('should return -1 when ...

JS (Error: Anticipated line breaks to be 'LF' but instead found 'CRLF'.eslintlinebreak-style) concern

Hello, I am new to JavaScript. I have created a table with checkbox rows and now I want to test it. However, I am encountering an error in my index.js file. Here is my code: import React from 'react'; import { Spin, Table } from 'antd' ...

conceal the submission button

How can I dynamically disable a save button when a specific value is selected from a dropdown menu? I have tried using CSS (display:none) and jQuery (attr) options but they are not working. Is there another method that I can use? $(document).ready(funct ...

What are the options for app directory routing and programmatic navigation in the upcoming 13 application

I am currently working on a project called Next 13 that involves using the app directory and MUI 5. The project's structure is organized as follows: ./src ./src/app ./src/app/dc ./src/app/dc/admin ./src/app/dc/admin/dc_types.jsx However, when I try t ...

Tips for toggling the appearance of like and add to cart icons

I am attempting to create a simple functionality for liking and adding items to a cart by clicking on the icons, which should immediately change the icon's color when clicked. However, I am facing an issue where the parent div's link is also bein ...

Fill a Vuetify select component with options from a JSON array

Having just started with VUEJS, I am facing a challenge in populating a vuetify select element with the names of countries from a local JSON file that contains an array of JSON objects. Instead of displaying the options correctly, it is creating individual ...

Webpage video stalling due to buffering

Currently, I am developing personalized video controls and have integrated a @progress event to monitor the video buffering progress and adjust the width of a progress bar div: <video @progress="videoBuffer($event)"> videoBuffer(e) { if ...

Updating the names of keys within an object that includes nested child objects

I am looking to update the keys in an object that contains nested objects with similar structures. Initially, my object looks like this: objs = { "one":{ "title":"bla", "amount":5, "children":[ { "title":"bla", ...

AJAX header with Hebrew letters

Whenever I use AJAX to send a file to a server, the code looks like this: $.ajax({ type: 'POST', async: true, crossDomain: true, url: 'http://' + address + '/api/file/upload', ...

The sluggish loading speed of the page is being caused by both jQuery and an external file containing Amazon

I am facing an issue with my website where it is loading over 1000 images per page from Amazon servers. To enhance the functionality, I have integrated jQuery plugins that are stored locally on the webserver, without using any remote JS or CSS. However, ...

Tips for preventing the playback of the sound while recording

When creating a basic JavaScript application that involves opening a stream from the user and analyzing frequencies, I found that while Google Chrome and Opera work well by providing feedback in the headphones, Firefox often remains silent. Additionally, F ...

What is preventing the async component from updating along with the route changes?

I have integrated async components into my CodeSandbox project (link provided above). I encountered an issue where clicking on "goto product-2" after "goto product-1" does not trigger any change. My expectation was for the <product-item> component ...

The directionalLight Properties do not yield any visible results

I recently experimented with the parameters in this code snippet but did not see any visible changes. The values for directionalLight.shadowCameraVisible, directionalLight.shadowCameraLeft, directionalLight.shadowCameraRight, directionalLight.shadowCameraB ...

Access a webpage in an html document using URL variables

In the process of developing an MVC web app without utilizing any MVC framework, I have created an index.html file with a section that dynamically loads all the views as needed by the user. However, I encountered an issue where direct URLs such as www.foo. ...

Sending Array and Form Data to Controller using MVC Ajax

In my jQuery code, I have an array of Objects that consists of customer data: function customersList() { this.selectedCustomers = []; } function customerObject(customerId, bookingId) { this.customerId = customerId; this.bookingId = bookingId; ...

What is the best way to include an image in front of a radio input using the jsonschema-form library?

I am currently utilizing the jsonschema-form library from Mozilla Services and I am seeking a way to include an image before a radio input. Here is an example of what the end result should look like: https://i.sstatic.net/glny8.png The JSONSchema I am w ...

Unable to load the manually added module in the /node_modules/ folder

I'm trying to manually use a module that I placed in the /node_modules/ directory. After copying and pasting the files and installing dependencies with npm, I encountered an issue while using NWJS 0.16.0. When attempting var speech = require('sp ...