VueJS does not update values instantly as they change

I have implemented a JS class with the following code:

class Field {
    public Value = null;
    public Items = [];
    public UniqueKey = null;

    public getItems() {
        let items = [...this.Items];
        items = items.filter((item) => {
            if (item.VisibleIf) {
                const matched = item.VisibleIf.match(/\$\[input:(.*?)\]/g);
                if (matched?.length) {
                    const srv = Service.getInstance();
                    for (let match of matched) {
                        match = match.slice(8, -1);
                        if (srv.Fields?.length) {
                            let found = srv.Fields.find((x) => x.UniqueKey === match);
                            if (found) {
                                item.VisibleIf = item.VisibleIf.replace(
                                    `$[input:${match}]`,
                                    found.Value ?? ''
                                );
                                return JSON.parse('' + eval(item.VisibleIf));
                            }
                        }
                    }
                }
            }
            return true;
        });
        return items;
    }

    public getInputTitle() {
        let title = this.Title;
        const matched = title.match(/\$\[input:(.*?)\]/g);
        if (matched?.length && title) {
            const srv = Service.getInstance();
            for (let match of matched) {
                match = match.slice(8, -1);
                if (srv.Fields?.length) {
                    let found = srv.Fields.find((x) => x.UniqueKey === match);
                    if (found) {
                        title = title.replace(`$[input:${match}]`, found.Value ?? '');
                    }
                }
            }
        }
        return title;
    }
}

Now I am working on a Vue component:

<div v-for="Field in Fields" :key="Field.UniqueKey">
    <v-select
        v-if="Field.Type == 'Select'"
        :label="Field.getInputTitle()"
        v-model="Field.Value"
        :items="Field.getItems()"
        item-text="Value"
        item-value="Id"
    />
    <v-input
        v-else-if="Field.Type == 'Input'"
        v-model="Field.Value"
        :label="Field.getInputTitle()"
    />
</div>

// JS
const srv = Service.getInstance();
Fields = srv.getFields(); // <- API call will be there.

The data is fetched from an API and has Title as Input $[input:uniqueKey]. The component loops over the data to generate fields. The getInputTitle function in the Field class works effectively. When typing into a field that other fields are dependent on, they change accordingly based on the $[input:uniqueKey] pattern.

A similar concept is applied in the getItems function, where upon typing into a field that exists in the VisibleIf property of the Items, such as '$[input:uniqueKey] < 1' or any valid JavaScript expression evaluated by eval. However, the getItems function is only called once during page load, unlike the getInputTitle which is called every time a user types into a field.

If more information is needed, feel free to ask. Appreciating any solutions. Thank you.

Answer №1

Within this block of code, you are updating the Object itself:

item.VisibleIf = item.VisibleIf.replace( `$[input:${match}]`, found.Value ?? '' );

Although you attempted to duplicate the array, you only created a shallow copy of the object here:

let items = [...this.Config.Items];

Here is a proposed solution:

const visibleIf = item.VisibleIf.replace(
    `$[input:${match}]`,
    found.Value ?? ''
);
const val = '' + helpers.evalExp('' + visibleIf);
if (helpers.isJSON(val)) {
    return JSON.parse(val);
}

Instead of modifying the original VisibleIf object, store it in a variable and use that instead.

I believe this approach will resolve your issue. Please let me know if it resolves the problem.

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

Enhancing Your Vue Experience: A Guide to Highlighting and Selecting HTML Elements on Mouse Hover

Incorporating a navigation header using Vue, I utilize v-html to display it seamlessly. Check out the demo - here <section class="text-gray-700 font-heading font-medium relative bg-gray-50 bg-opacity-50"> <nav class="flex justify ...

Navigating through the React components using react-router and accessing the props can

Is there a way to access this.props from the <Router>'s onUpdate function? I need to know the current route and access this.props.route in order to identify the page (name). Unfortunately, I haven't found any resources on how to achieve thi ...

Adjusting speed dynamically within a setInterval function in JavaScript

I am working on a react application that requires displaying text with varying intervals between sentences, one at a time. To achieve this functionality, I stored all the sentences in an array and implemented a setInterval function: startShowingText() ...

Retrieve the values of two inputs from outside of the event

How can I access the values of two input fields in order to perform calculations as soon as their values are updated? <script> // Accessing the values of the two input fields for immediate calculation based on user input const heightInputEl = docum ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

Calling a JavaScript function from server-side code (without using startup scripts)

In essence, my objective is as follows: Initiate deletion of a record upon button click. Delete the record only if a specific column (Location) is null (working perfectly). If the specific column is not null, prompt the user for confirmation before proce ...

Create a PHP form that includes text and image inputs with the help of AdminLTE and integrates DropZone.js

I have been working with a template from adminLTE and you can check it out at the following link: . At this point, I am trying to upload images first and then use the image names as input text elements in my main form for submission. However, I have encou ...

Struggling to make Vue.js transition effects function properly?

I'm having trouble getting a vue.js (version 1) transition to work. I copied the code from their official website, but it's not running the javascript console.logs! Vue.transition('fade', { css: false, enter: function ( ...

Is there a way to retrieve the id of a Vue component programmatically in Vue2?

Hey everyone, I have a scenario where I'm working with a VueComponent and I need to pass it to $vuetify.goTo() in order to scroll the page to that specific component. Sadly, while $vuetify.goto() supposedly accepts a VueComponent, it actually requires ...

What significance does comparing two arrays hold in the realm of Javascript?

While working in my node.js REPL, I have created 4 arrays: a = [1,2,3], b=[], c=[4,5], d=null (although d is not actually an array). I decided to compare them directly like this: > b = [] [] > a > b true > b > a false > a > c false & ...

Refreshing the child component based on the child's action and sending information to the parent in a React application

Within my Parent Component, I am utilizing an Ajax call to populate two children Components. C1 requires the data only once, while C2 has the ability to fetch additional data through subsequent Ajax calls and needs to render accordingly. I find it more co ...

Algolia's Vue InstantSearch: a split between two separate facets

While using algolia vue-instantsearch, I have come across a unique scenario that is proving to be quite challenging to solve. The usual refinement behavior is such that the results should match all the applied refinement filters. However, I need to intro ...

Is it possible to retrieve JSON data and display only the entries with positive values in an HTML

I am working on a project that involves fetching JSON API data and displaying it in an HTML table, but only for values above 10. Below is the code snippet along with my JavaScript. I specifically want to exclude negative values and only display positive v ...

Inserting a Specific Iframe into a Designated Location in HTML with the Help of Jquery

Currently, I am encountering an issue with placing a dynamically created iframe inside a specific section of my webpage. The iframe is supposed to be contained within a div element named "maps", but instead it is appearing at the bottom of the page.This ma ...

Ways to remove specific characters from the escape() function in express-validators

When using the check method from express-validator to validate user input, I'm curious if there's a way to exclude certain characters from the test. For example, currently I have: check("profile.about").trim().escape() This code snippet convert ...

It seems that the `to` required prop was missing in the `Link` component of React-Router

Currently, I am facing an issue while trying to integrate react-router. The error message I'm encountering is: Failed propType: Required prop to was not specified in Link. Check the render method of app. Unfortunately, I am unable to pinpoint ex ...

Acquiring the markers, however the latitude and longitude are both null - vue.js

I have been working on displaying markers on a map. When I fetched the data, everything seemed fine in Vue DevTools. The `this.markers` property also contains the data. However, to my surprise, the values for `lat` and `lng` inside the markers are showing ...

Displaying dates on the Amcharts category axis for instances with empty data

I am currently creating a fruit consumption chart for each day, and so far everything is working correctly in the provided example. var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "hideCredits": true, "fixedColumnWidth": '10px& ...

Safari displays the contents of JSON files instead of automatically downloading them

I am facing an issue with a JavaScript code that generates a link to download a JSON file. The link is structured like this: <a href="data:text/json;charset=utf-8,..." download="foo.json">download</a> While the link works perfectly in Chrome ...

What limitations prevent me from using "await .getAttribute()" in Protractor, despite the fact that it does return a promise?

I have been working on transitioning my Protractor tests from using the selenium control flow to async/await. However, I am facing an issue where it is not allowing me to use await for the .getAttribute() function. Each time I try, I receive the error mess ...