Component updates are not working in VueJS

My Vue 1 component requires an object as a prop that needs to be filled by the user. This object has a specific structure with properties and nested inputs.

The component is essentially a modal with a table containing necessary inputs. I want to perform validations, calculations, and style changes based on user input.

When the modal is loaded, I set the models of the inputs using their unique ids like this:

v-model="object.inputs[subgroup[1].dx.mob.id].comment"

However, despite setting values, the page does not re-render correctly. The <input> fields do not retain the values, disappearing once clicked away.

I have tried various solutions like dynamically building watchers for each input or returning inputs in a computed property, but none seem to work effectively. Even manually triggering this.$forceUpdate() does not update the page as expected.

The only workaround I found was to recreate the component entirely, which is not ideal due to performance issues.

If anyone has a better solution, I would greatly appreciate it!

Temporary Fix: Despite multiple failed attempts, I found an unconventional approach to forcing the component to re-render by utilizing a new variable called key.

This involves creating an update function tied to the @blur event of every input/select element, triggering a change in the key value and ultimately prompting a re-render of the component.

... 
data: function() {
      return {
        ... ,
        key: 0
      };   
},

...

methods: {
    ... ,
    update: function(){
        this.key = this.key == 0 ? 1 : 0
    }
},
computed: {
    ... ,
    testData: function () {  
        var data = []
        var __self = this
        var blu = this.key // Reading the key here triggers the re-render
        console.log(blu)
        this.test.inputs.forEach(function(input){

            var slug = input.slug.replaceAll('#', '').split('-')
        
            __self.setItem(data, slug, input)

        })
     
        console.log('data', data)
        return data 
    } 
}


Answer №1

Improved Solution

After some careful debugging, I was able to find a solution to the issue at hand.

The component described in my initial question is utilized on two different pages: one for creating and one for editing. It dawned on me when I realized that everything worked smoothly on the editing page.

Here's What Was Going On:

The key difference between how the component functioned on the two pages was the data being passed to it. In the editing page, all the objects already had data filled in, while in the creation page, they were blank as expected.

In order to work with a usable object, I had to populate it with empty inputs so that I could manipulate them later.

Initially, I erroneously tried to set the property manually like this:

objects[index].inputs = {}

I assumed that assigning a property to a reactive object would automatically make it reactive too, but boy was I mistaken.

Understanding Vue Reactive Properties:

To enable reactivity in Vue, the framework overrides the default getters and setters of the Object class, under certain conditions:

  • The property must be added using Vue.set() or this.$set()
  • All parent properties must also be reactive

Despite several attempts, setting objects[index].inputs = {}, and then using this.$set() to fill in the inputs still didn't work because I hadn't made .inputs reactive.

So, I had to:

this.$set('objects[${index}].inputs', {})

prior to

this.$set(`objects[${index}].inputs[${input.id}].value`, null)
this.$set(`objects[${index}].inputs[${input.id}].comment`, null)

In Conclusion:

If you encounter reactivity issues, my advice is to log the object in question and verify if both the object and its parent have the necessary getters and setters.

Remember, when adding new properties to a reactive object, always use $set().

Reactive Object Example:

https://i.sstatic.net/tmi27.png

Non-Reactive Object Example:

https://i.sstatic.net/sIvyg.png

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

Learn how to dynamically update the dropdown text in bootstrap-vue.js

This is the dropdown code I am currently using: <b-dropdown size="sm" text="Update" split class="m-2"> <b-dropdown-item-button>Action</b-dropdown-item-button> <b-dropdown-item-button>Another ...

Survey with results routing based on rating

I am looking to incorporate a basic survey on my website featuring a few multiple choice questions. Each question will be assigned a score, and upon completing the survey, users will be redirected to a personalized page based on their overall score. Doe ...

Incorporating multiple web services into a React JS project to populate a Material UI dropdown efficiently

I have some code that is calling a web service and I have a few questions. Firstly, what is the best way to call a second web service? Currently, I am calling one and displaying the data in a list. But if I need to call a second web service, should I also ...

Is there a way to confirm that the content of two files is identical?

Currently, I am utilizing mocha/supertest/should.js for testing a REST Service. When I make a request to GET /files/<hash>, it returns the file as a stream. I am seeking guidance on how to use should.js to assert that the contents of the file are i ...

Obtaining the local IP address of my system with React JS

Is there a way to retrieve the local IP of my computer within a React JS application? I would appreciate any suggestions on how to accomplish this. ...

Validating forms using ajax, php, and mysql for seamless user input processing

I'm currently in the process of creating a login form that includes an instant email address verification feature against my database. Despite my efforts and attempts to make this functionality work, I have faced challenges in getting it to function ...

What is the best way to modify the styling of my CSS attributes?

I'm currently working with this CSS code: input:checked + .selectablelabel .check { visibility: hidden; } Now, I want to change the visibility property to "visible" using JavaScript. I attempted the following: $(document).on('click', & ...

Steps to establish a connection with a remote MYSQL database using the actual IP address in Node.js

In my Nodejs file, I have set up the connection as follows. The issue arises when attempting to connect to the remote database on a server. module.exports = { host: '234.32432.32432',//this is an example IP address and not a real one. use ...

The Laravel 8/Passport/GuzzleHttp API request successfully returns a status code of 200, however, there is no response

Currently, I am in the process of setting up a login page using Vue.js (front-end) with Laravel 8 (back-end), incorporating Passport and GuzzleHttp. The oAuth/Token functionality has been successfully tested using Insomnia. Additionally, the userData retr ...

Automatically create the web.config file upon executing the command "npm run build"

My Vue app is hosted on IIS. In order to follow the instructions here, I need a custom web.config file in the dist folder. The issue I am facing is that whenever I run "npm run build", the entire dist folder gets deleted, including my web.config file. I th ...

Is the asynchronous nature of setState truly reliable?

As I delve into learning React, an interesting topic that keeps popping up is the async nature of setState. It's often mentioned that if you try to console.log(state) immediately after calling setState, it will display the old value instead of the upd ...

Unable to establish proper functionality of username variables in Node.js chat application

For my latest project, I am developing a chat application in node.js following a tutorial from socket.io. The main objective of the app is to allow users to input their username along with a message, which will then be displayed as "username: message" in t ...

Postgres Array intersection: finding elements common to two arrays

I'm currently developing a search function based on tags, within a table structure like this CREATE TABLE permission ( id serial primary key, tags varchar(255)[], ); After adding a row with the tags "artist" and "default," I aim ...

Implementing webpack and service workers in Vue.js: a comprehensive guide

At this moment, the package.json for my vue app looks like this: { "name": "App", "version": "0.1.2", "private": true, "scripts": { "serve": "vue-cli-service serve" ...

Converting primary key strings to BSON for the _id field in MongoDB using Mongoskin

The primary key in Mongodb is typically _id and its data type is bson. For example: {_id : "4e7020cb7cac81af7136236b"} I am interested in setting another field's value as the primary key. For instance: apple How can I convert the string "apple" to ...

A guide to creating a TypeScript redux middleware class

As specified in the typescript definition for Redux, these interfaces must be implemented to create middleware: /* middleware */ export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> { dispatch: D getState(): S } /** * A midd ...

Activate a monitoring pixel with a click of your mouse

I have a tracking pixel that is typically placed in the body of a "installation success" page: <img src="http://domain.com/adclick.php" width="1" height="1" border="0" /> However, I want to trigger this pixel when someone clicks on a download butto ...

Troubleshooting: Angular ng-if not correctly detecting empty strings

When looking at my code, I have the following snippet to showcase data from angular scope variables. The initial two lines are functioning correctly and displaying data from the scope variables; however, there seems to be an issue with the line using ng- ...

Ways to make nodejs return a different value instead of an object promise

Within my user.js file, I have an async function designed to retrieve the avatar's location from the database. The code for this operation is as follows: async findavatar(username) { const sql = `SELECT image FROM users WHERE user = "${userna ...

import a function from jQuery that has been defined in an external JavaScript file

Whenever I attempt to execute this action, I encounter an error stating that the function is undefined $(function () { function Example(){ Example1(); } Example1(); }); external.js $(function () { function Example1(){ alert("Hello"); } }); ...