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

How can I access files from another docker volume in a Vue and Laravel environment?

I have a current project running with Vue & Laravel on docker. Check out the project structure and setup details here Currently, I am facing an issue with uploading images to the server. When running the project without docker, everything works fine as e ...

What can be done to resolve the error message "This language feature is only supported for ECMASCRIPT6 mode" in Google Tag Manager?

I attempted to implement some JavaScript code in GTM, but encountered an error. The error occurs at this line window.sbHooks.addAction('sbCoreState::CreateBets/success', (data, response) => { where I utilized a custom Vue.js hook. How can I ...

Managing date validation for a three-part field using AngularJS

I am currently working on validating a three-part date field using AngularJS. I have managed to create a custom validation function, but I am struggling with determining how the fields should update each other's status. How can I ensure that all thre ...

Changing the order of elements in a JavaScript array

Issue: Develop a function that accepts an array as input and outputs a new array where the first and last elements are switched. The initial array will always be at least 2 elements long (for example, [1,5,10,-2] should result in [-2,5,10,1]). Here is ...

Is there a way to dynamically change the height in jQuery/JavaScript?

I am encountering an issue with my embed code where the height changes randomly after a few seconds, depending on certain parameters. Here is an example of the code I am using: $( <embed></embed>) .attr("src", "http://www.bbs.com") ...

Using AngularJS client and Flask server for a RESTful call, one can include the

I am currently facing an issue where I need to send a REST request from my AngularJs client to a Flask server. The problem arises when one of the ids (key) in the request contains a forward slash. Interestingly, if the key does not contain a slash, the re ...

Utilize the HTML img tag in conjunction with AngularJS and Ionic to showcase dynamic images

Currently, I am working on a hybrid mobile app using ionic and Angularjs. I am facing an issue with displaying images through the img html tag in my app. The main layout of my page includes a carousel at the top that displays images and a list containing s ...

Listening for an event or using a CSS pseudo-class to detect when the scrollbar becomes

Are there any JavaScript event listeners or CSS pseudo classes that can detect when a scrollbar appears and disappears? For example, on Mac OS and Windows Internet Explorer 10 or newer, the scrollbars are hidden by default but appear when scrolling begins. ...

Tips for adjusting the language settings on a date picker

Is there a way to change the language from English to French when selecting a month? I believe I need to configure something in the core.module.ts. How can I achieve this? https://i.sstatic.net/Cpl08.png @NgModule({ declarations: [], imports: [ Co ...

Tips for accessing a variable through request.query

When I made a call to getContents() in my client-side code: $.getJSon("/getContents", function(room){ theRoom=$("#roomName").val();//textarea's value ... }); I am now trying to figure out how to retrieve theRoom variable in getContents(), which is ...

Transforming Uint8Array into BigInt using Javascript

I've come across 3 different ways to convert a Uint8Array to BigInt, but each method seems to produce varying results. Can someone clarify which approach is correct and recommended? Utilizing the bigint-conversion library. The function bigintConversi ...

Steps for adding a div to a Vue template

When working with my template, I utilize a for loop to iterate through data entries. <tr v-for="entry in filteredData"> <td> @{{ entry.position}} </td> <td :class="addNewElement(entry.value)"> </td> <td> ...

How to stop a checkbox from being selected in Angular 2

I have a table with checkboxes in each row. The table header contains a Check All checkbox that can toggle all the checkboxes in the table rows. I want to implement a feature where, if the number of checkboxes exceeds a certain limit, an error message is ...

Connect button with entry field

I want to create a connection between an input element and a button, where the button triggers the input and the input remains hidden. Here is a solution that I came across: <a href="javascript:void(0)" id="files" href=""> <button id="uploadDe ...

When using @testing-library/react (rtl), the 'waitFor' function achieves success even without the need for the 'await' keyword

waitFor() is causing my test to fail while waitFor() (without await) makes it pass. The official documentation states: Async methods return a Promise, so you must always use await or .then(done) when calling them. (https://testing-library.com/docs/guide ...

What is the proper way to add an object to an array within an object in TypeScript?

import {Schedule} from './schedule.model'; export class ScheduleService{ private schedules:Schedule[]=[ new Schedule("5:00","reading"), new Schedule("6:00","writing"), new Schedule("7:00","cleaning") ]; getSchedule(){ ret ...

Utilizing a Dependency Injection container effectively

I am venturing into the world of creating a Node.js backend for the first time after previously working with ASP.NET Core. I am interested in utilizing a DI Container and incorporating controllers into my project. In ASP.NET Core, a new instance of the c ...

Utilizing JavaScript to trigger an email with PHP variables included

i am trying to pass a few php variables using a javascript trigger. Everything seems to be working with the variables, databases, and script but I am struggling with the PHP part. Here is my attempt at the PHP code, although it clearly has some issues. I ...

Problem with Next.js router language settings

I have configured different locales for our application including uk and us. For the blog section, we can use either us/blog or just /blog for the uk locale. After switching to the us locale like this: (locale = "us") const updateRoute = (locale ...

The integration of express and cors() is malfunctioning

Currently, I am developing a React application and facing an issue while trying to make an API call to https://itunes.apple.com/search?term=jack+johnson In my project, there is a helper file named requestHelper.js with the following content : import &apo ...