When an unrelated value is changed, the Vue 2 dynamic component experiences a loss of its values during the refresh

I've been grappling with this issue for quite some time now and I'm beginning to suspect it might be a bug.

I'm currently utilizing a dynamic vue component to substitute markers in a body of text with input fields. The functionality seems to be working as intended:

hydrateBaselineQuestion(targetObject) {
            var html = '<p>'
            
            html = html + targetObject.baseline

            if (targetObject.baseline_questions) {
                targetObject.baseline_questions.forEach((questionData, index) => {
                    var counter = index + 1,
                        placeholder

                    if (typeof questionData.placeholder_text === 'undefined' || !questionData.placeholder_text || questionData.placeholder_text === null) {
                        placeholder = 'Enter value'
                    }
                    else {
                        placeholder = questionData.placeholder_text
                    }
                    
                    switch (questionData.input_type) {
                        case "select":
                            // html = html.replace('<' + counter + '>', '<input-inline-select v-model="componentBaselineAnswers[' + index + ']" :data="questionData[' + index + ']"></input-inline-select>')
                            html = html.replace('<' + counter + '>', `<select class="c-input-inline-select mx-1" v-model="proxyValue[${index}]"><option v-for="(option, index) in componentQuestionData[${index}].options.split(',')" :key="index" :value="option">{{option}}</option></select>`)
                            break;
                        case "text":
                            html = html.replace('<' + counter + '>', `<input class="c-inline-input" type="text" v-model="proxyValue[${index}]" placeholder="${placeholder}" />`)
                        default:
                            break;
                    }
                })
            }

            html = html + '</p>'

            return {
                template: html,
                data: () => ({
                    componentQuestionData: targetObject.baseline_questions,
                    proxyValue: []
                }),

                watch: {
                    proxyValue(newValue) {
                        console.log('proxyvalue: ' + newValue)
                        // this.$emit('input', newValue)
                    }
                },

                mounted() {
                    console.log('mounted')
                    console.log(this.proxyValue)
                },
                created() {
                    // this.proxyValue = this.value
                    console.log('created')
                    console.log(this.proxyValue)
                },
                updated() {
                    console.log('updated')
                    console.log(this.proxyValue)
                }
            }
        },

The issue arises when I modify an unrelated value, causing the dynamic vue component to refresh and erase all input data. I have provided a demonstration of the problem here: https://codesandbox.io/s/vue-2-playground-forked-pc7q4n?file=/src/App.vue

Upon changing the value in the select input below (linked to a model named period), all form data gets cleared.

I also attempted a v-model approach to bind the data to the component. You can view it here: https://codesandbox.io/s/vue-2-playground-forked-bt766f?file=/src/App.vue. It somewhat resolves the issue but every time I input a character into a textbox, it loses focus.

Could someone shed light on why this occurs and provide a solution to prevent it?

Answer №1

I'm not completely certain if the link I shared includes my modifications, but I did switch your hydrate method to a computed property and it appears to be functioning correctly now.

https://codesandbox.io/s/pc7q4n

EDIT

It seems my changes were not included after all, but regardless, I suggest moving that hydrate method to a computed property and utilizing this.commitmentTarget instead of targetObject within the hydrateBaselineQuestion function. Please let me know if you require further clarification!

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

What is the best way to create text boxes that can expand and collapse within a UIWebView?

I am looking to present text in a UIWebView with expandable or collapsible boxes that contain titles. The user should be able to tap the bar of a collapsed box to expand it. Is there a simple solution available that can be easily integrated into a local ...

Angular Pause until the variable is ready

I am in the process of developing a new web application service. The first step involves obtaining a token through the rest API. Once this token is obtained, it needs to be sent as a header to retrieve additional information. The issue I'm facing is ...

Guide on retrieving the mouse button press from a command event using XUL

There appears to be a difference between the XUL command and click events. While my function is called when using the command event, the event object does not include the button property. I'm trying to figure out: how can I determine which mouse but ...

How can I gather information from members who have already signed up?

I have a form that submits data to the Angular Firebase database. Once the form is submitted, I want to display the previously submitted data in the form if the user signs in again. Below is my .ts file: import { Component, OnInit } from '@angular/c ...

What is the best approach for rendering content to a page in ReactJS when a user clicks on a dynamic URL?

One challenge I am currently tackling is how to direct users to a specific page when they click on a dynamic URL. Specifically, within my "product_list" API data, there exists a key called "url". Upon clicking this "url", the user should be redirected to a ...

Vue.js 2 components encountering issue with parent-child relationship due to undefined item

I recently started working with Vue and encountered the error referenceError: items is not defined. Can anyone help me figure out why this error is occurring or provide some guidance? Upon initial inspection of the code, it seems like the issue may be rel ...

What is the best way to conceal a dropdown menu when the page first loads?

I have a dropdown menu that is displaying like this: <ul> <li class="dropdown open"> <a aria-expanded="true" href="#" class="dropdown-toggle waves-effect waves-button waves-classic" data-toggle="dropdown"> <spa ...

Create a dynamic image showcase using PHP or JavaScript

So I have a large collection of car photos organized in a structure similar to this (this is just a fictional example to illustrate my idea): Cars > Audi > Sports cars > '5 pictures' Cars > Audi > Family cars > '3 pictur ...

Turning a JavaScript function into jQuery

Is there a way to convert this JavaScript selected code into jQuery? I need to target a button class instead of an ID, and I've heard that using jQuery is the simplest way to achieve this. var playButton1 = $('.playButton1'); playButton1.o ...

Is it possible to declare variables within a React 'render' function?

I have data arranged in multiple columns on several rows, with a react element corresponding to each data element. The number of elements on the first row can vary between 4 and 6. For instance, I may display a user's name, birthday, and email. If t ...

Utilizing a React hook within an event listener

I have developed a custom hook for playing audio in react, here is the code: "use client"; import { useEffect, useState } from "react"; export const useAudio = (url: string) => { const [audio, setAudio] = useState<HTMLAudioE ...

The function WebGLRenderer() from three.js allows for rendering in

When initializing the WebGLRenderer, I am passing in a canvas DOM element like shown below: var jqc = $('#myCanvas'); //accessing canvas with jQuery; var par = {canvas:jqc.get()}; //creating parameter object with canvas DOM element var renderer ...

Trouble generating document with Firebase setDoc()

In my current project, I am successfully creating a new user with authentication and then using the generated UID to create a new document. Here is the code snippet: const currentUser = await auth.createUserWithEmailAndPassword(email, pass); consol ...

Top method for stacking several divs in a vertical line

In search of the most effective method for organizing numerous dynamically generated divs (all with identical widths) in a vertical stack, two potential solutions have emerged: Utilize float:left... Implement an unordered list and enclose each div within ...

vue-chartjs is experiencing difficulties when it comes to showing the labels and datasets

I'm having an issue with my line-chart. The data from the api/controller isn't showing up on the chart, even though the response contains all the data. https://i.stack.imgur.com/PWZxZ.png As shown in the image, the line-chart is empty but the r ...

Is it beneficial to rotate an image before presenting it?

I am looking for a way to display a landscape image in portrait orientation within a 2-panel view without altering the original file. The challenge I am facing is that the image size is set before rotation, causing spacing issues with DOM elements. Is ther ...

Is it possible to navigate between jQuery EditInPlace fields using the Tab key?

Seeking advice on implementing tab functionality for a page with multiple jquery EditInPlace fields. The goal is to allow users to navigate between fields by pressing the tab key. Currently using the 'jquery-in-place-editor' plugin available at: ...

Attempting to pass data to a v-for loop in Vue, but it seems like I am overlooking a crucial detail

Is it correct to use v-for in HTML or should I not use v-for in Vue3? The 'items:' is defined but never used, but when I try to use it in iteration with v-for, how can I fix this issue? I am unsure of the proper way to do it. <template> ...

How can you display or conceal an HTML page in Jquery Mobile?

This code snippet is used for toggling the visibility of a div. $("[id*=viewMeButton]").click(function(){ $("[id*=viewMe]").toggle(); $("[id*=viewMeButton]").show(); }); In Jquery Mobile, similar functionality can be implemented to show/hide a ...

Ways to update list item text with jQuery

I am attempting to create a button that can replace the content of a list item. Although I have looked at other solutions, I keep encountering this error message: Uncaught TypeError: Object li#element2 has no method 'replaceWith' I have experime ...