The v-model for a particular field is not reflecting real-time updates like the other fields with the same datatype. I'm trying to figure out what could be causing this issue

In my specific model, there are various values that can be updated through a form on the webpage. These values include "Quantity", "Rate", "Amount", "Net rate", and more.

The problem I am facing is with binding these values with my inputs using v-model. Everything works perfectly for all fields except the "net rate" field! It doesn't update in real-time like the other fields do. Strangely, when I manually refresh Vue-devtools UI after making changes in the field, it updates correctly. This issue seems to be isolated to the "net_rate" field only.

I'm confused about what might be causing this issue. Here is the code snippet where the first field with id discount_perc updates instantly, but the net_rate field does not:

<div class="inline-form-group col-sm-12 col-md-4 col-lg-1 text-right">
    <label for="discount_perc" style="color:teal;font-size:14px;">Dis %</label>
    <input type="text" ref="discount_perc" @keydown.enter="$refs.net_rate.focus()" @input="setAmount()" v-model="selectedItem.discount_perc" class="form-control text-right" />
</div>
<div class="inline-form-group col-sm-12 col-md-4 col-lg-1 text-right">
    <label for="net_rate" style="color:teal;font-size:14px;">Net rate</label>
    <input type="text" ref="net_rate" v-model="selectedItem.net_rate" @input="updateAmount()" @keydown.enter="addItem()" @keydown.tab="addItem()" class="form-control text-right" />
</div>

Below are the methods triggered by input events for both fields:

setAmount: function () {
    var discount_percAmount = this.selectedItem.discount_perc ? (this.selectedItem.discount_perc * this.selectedItem.price) / 100 : 0;
    this.selectedItem.net_rate = this.selectedItem.price - discount_percAmount;

    if (this.selectedItem.size_breadth > 0 && this.selectedItem.size_length > 0) {
        this.selectedItem.item_amt = this.selectedItem.net_rate * this.selectedItem.quantity * this.selectedItem.size_breadth * this.selectedItem.size_length;
    } else {
        this.selectedItem.item_amt = this.selectedItem.net_rate * this.selectedItem.quantity;
    }
},
updateAmount: function () {
    if (this.selectedItem.size_breadth > 0 && this.selectedItem.size_length > 0) {
        this.selectedItem.item_amt = parseFloat(this.selectedItem.net_rate) * this.selectedItem.quantity * this.selectedItem.size_breadth * this.selectedItem.size_length;
    } else {
        this.selectedItem.item_amt = parseFloat(this.selectedItem.net_rate) * this.selectedItem.quantity;
    }
},

I acknowledge there is a redundant piece of code that can be refactored into a method, but my current focus is on resolving this issue.

I inserted an alert to display the calculated value of net_rate in the updateAmount() function, and it shows up correctly. However, the value is not updating in the model without a manual refresh. I've been trying to troubleshoot this for over 24 hours with no success.

Has anyone encountered a similar problem before? Any insights or solutions would be greatly appreciated!

UPDATE: Below is my data structure.

data () {
    return {
        availableParties: [],
        party: [],
        availableArchitechs: [],
        availableStaff: [],
        availableLocations: [],
        location: '',
        availableItemCodes: [],
        selectedItem: [],
        quotation: {
            party_id: null, date: new Date().toISOString().split('T')[0], architech: '', staff: '', items: [], order_no: '',
            item_amt: 0, gst_0_amt: 0, gst_5_amt: 0, gst_12_amt: 0, gst_18_amt: 0, gst_28_amt: 0, final_amt: 0
        },
        latestQuotation: [],
        partySpecificItemInfo: {
            rate: 0,
            discount_perc: 0,
            net_rate: 0
        },
        updateAllowed: true,
        selectedItemImageExist: false,
    }
},

Answer №1

The issue at hand arises when you initialize an Array in VueJS within your data property, which is observable. However, if you later replace it with an Object in your function, that Object is no longer observable. To address this, you can either make the object observable as well or simply set it as an Object by default so that it is already observable. Then, utilize Vue.set to add properties to the object that will be observable.

To ensure it is an object by default:

selectedItem: {}, 

When working on the object, use Vue.set:

Vue.set(this.selectedItem, 'property', value)

Replace property with specific names like net_rate, and substitute value with the desired value for that property within the object.

With these adjustments, the object will become reactive with the attached observer, ensuring that values update correctly.

Check out the Vue.set documentation for more details.

It's important to note this excerpt from the docs:

Vue cannot detect normal property additions (e.g. this.myObject.newProperty = 'hi')

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

Tips for converting the Instagram cURL post request to a JavaScript request

I am attempting to convert the code I received from Instagram into a token. The code provided in the Instagram DOCS uses a curl request, but I would like to implement it using JavaScript instead. Here is how the original code looks: curl -X POST &bsol ...

Having difficulty installing npm due to version issues while working with Vue

What steps should I take to troubleshoot this issue? PS C:\xampp\htdocs\MOA\agri-app> npm install npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/em ...

Tips for dynamically styling a Styled Component with all the CSS housed in an external file

My goal is to dynamically render a Styled Component. In the past, it was simple because all styling was contained within the component itself. However, I now strive to maintain a separation of concerns by storing the CSS in an external file. While this app ...

Is there a way to change the projection of id in mongoose?

I have a microservice in Node.js, where I am using Mongoose to retrieve a document from my mongoDB. The document has multiple properties, but I only need to display 3 of them: The properties I want to display are '_id' as 'id', 'n ...

Creating: A Pair of Vue Components with Matching Sass Styles

As I ponder on the best way to structure my Vue components, I am faced with a dilemma. Two of my Vue components share the same sass code, yet they have different markup, state, and methods. I am seeking a solution to reduce repetition of sass code across t ...

Creating customizable Isotope objects using custom CSS margins that are influenced by the child-nth selector and JavaScript

My recent project involved creating a simple .isotope gallery, and when viewing the selected #portfolio-wrap container in Chrome Dev Tools, here is how it appears: Unfortunately, I am unable to upload three links here. Please visit this link for more info ...

When you click on a main category, a list of its corresponding subcategories will

concept image My vision involves having users click on a category from the top menu to display all main cards (parent cards), and then further clicking on a parent card will unveil its corresponding child cards. I've even included an image to help v ...

Bringing Typescript functions into the current module's scope

Is it possible to import and reference a module (a collection of functions) in typescript without the need for the Module. prefix? For instance: import * as Operations from './Operations'; Can I access Operations.example() simply as example()? ...

Ways to create a new line in JSX using a JavaScript string

My JSX contains a string that I utilize: const message = 'Hello World'; and in my JSX: <p>{message}</p> Is there a way to start a new line from World? The desired output is: Hello World ...

Using Vue CLI to dynamically import modules from project directories

Is it possible to import components from a bundled webpack file using dynamic imports? const url = '${window.location.origin}/assets/default/js/bundle/vue_data.bundle.js'; this.getAxiosInstance().get(url).then(response => { ...

Retrieving the data from a GET request to use in a subsequent request

I'm currently utilizing Vue to interact with an external API on a Drupal website. In order to make this interaction dynamic for each Drupal user, I need to fetch a token from Drupal first. My approach involves making two GET requests. The initial requ ...

Creating a Vue.js transition that causes an icon to slide upwards along with an expanding panel

My goal is to implement a panel that expands from the bottom of the screen when an icon is clicked. I am utilizing Vue.js transition for animating the panel sliding in from below. However, I encountered an issue where the icon instantly jumps to its final ...

The CSS transition fails to function correctly when rendering a React element within an array

When rendering a React component within an array using CSS transitions, I noticed that the elements in the array re-order and change style. Surprisingly, only the elements moving up have transitions applied, while the ones moving down do not. I expect all ...

404 Response Generated by Express Routes

Exploring the MEAN stack has been a great way for me to expand my knowledge of node and express. Currently, I am working on creating a simple link between two static pages within the app. My routes are set up as follows: //Home route var index = require( ...

Utilizing Wordpress for Geocoding with a map or directions

I'm currently working on setting up a Wordpress page where users can specify a location either by entering an address or browsing a map. However, I am encountering an issue with the map not loading on the page () despite verifying the API Key and the ...

The jsx file is not being parsed by Webpack

In my current project, I am working with a JSX file that contains React code. import React from 'react'; import {render} from 'react-dom'; class App extends React.Component { render () { return <p> Hello React!</p>; ...

Retrieve information from an express server using the fetch API

I am attempting to use the alert function to display a variable string in Express's .get() method and then send it using res. I want the alert to show "I am working fetch". This is my server.js var express = require('express'); var app = e ...

Convert HTML element to a JSON object

Here is an example of an HTML element: <div class='myparent'> <div> <div class="pdp-product-price"> <span> 650 rupees</span> <div class="origin-block"> <sp ...

The function setAttribute does not work with arrays

I'm facing an issue where I need to conditionally assign an attribute to each item in an array based on a radio button value. I have been able to set the required attribute on individual items, but I'm struggling to apply it to all elements in th ...

Is there a way to display an animation when a page loads using jQuery that only plays for index.php and not other_page.php?

How can I trigger an animation on page load, specifically for my index.php page and not all other pages on my website? Is there a jQuery function that targets only the index.php page like this: $('index.php').ready(function()); If not, what i ...