Customizing data attributes for child components in Vue 2

In my Vue project, I have created a multi-page questionnaire using the v-show directive within a container called RiskAssessmentTest.vue.

To handle loading questionnaire drafts, I have a component named RiskAssessmentDrafts.vue, which has the following structure:

<template>
    <div>
        <button type="button" class="btn btn-success btn-block rounded" @click="loadDraft(draft)">Continue</button>
    </div>
</template>

<script>
    import Progress from 'easy-circular-progress';
    import moment from 'moment';

    export default {
        components: {
            Progress
        },
        data() {
            return {
                moment: moment
            };
        },
        props: ['drafts'],
        methods: {
            loadDraft(draft) {
                this.$emit('load-draft', draft);
            },
        }
    };
</script>

<style></style>

The above component emits the loadDraft() method to the parent component as shown below:

<template>
<risk-assessment-drafts :drafts="drafts" @load-draft="loadDraftAnswers" />
</template

The loadDraftAnswers() method fetches and loads the questionnaire data for each respective question in the child component.

/**
 * Load any draft answers into each question page.
 *
 * @param {*} $draft
 */
async loadDraftAnswers($draft) {
    this.$refs.q1.loadDraftAnswers($draft['test_id'], 0);
    this.$refs.q2.loadDraftAnswers($draft['test_id'], 1);
    this.$refs.q3.loadDraftAnswers($draft['test_id'], 2);
    this.$refs.q4.loadDraftAnswers($draft['test_id'], 3);
    this.$refs.q5.loadDraftAnswers($draft['test_id'], 4);
},

After checking the Chrome dev tools, it seems like the data is initially set, but upon further inspection, everything becomes unset when clicking on the component again.

This behavior raises questions about data retention in Vue components, especially when using directives like v-if. Is there a way to ensure that the component retains its data consistently?

You can view a video demonstration of the issue here:

Answer №1

After some investigation, I discovered that the issue stemmed from using a v-if in another part of the same template. Strangely enough, this was causing the components on the first and last pages to be destroyed.

In simple terms, the data was being loaded into the component only to be immediately destroyed. As a result, Vue either couldn't find where to push the data or mistakenly added it to the wrong page.

I came across this problem by tracking the lifecycle events using created and destroyed:

created() {
    // console.log('Page ' + this.current_page + ' was created in the created hook');
},

destroyed() {
    // console.log('Page ' + this.current_page + ' was destroyed');
},

This might be considered a beginner's mistake, but if anyone encounters a similar issue, hopefully this explanation can help you navigate through it.

(Along with the comments mentioned above).

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

JavaScript - Receiving alert - AC_RunActiveContent.js needed for this page to function

When I attempt to open the HTML file in my application, a pop-up message appears stating that "This page requires AC_RunActiveContent.js." However, I have already imported and referenced the AC_RunActiveContent.js file in my package. Can someone assist m ...

What is the best way to create a flexible Ul-LI menu?

Is it possible to create a flexible menu where clicking on an item does not cover other items in the menu? #demo { margin: 30px 0 50px 0; font-family: sans-serif; } #demo .wrapper { display: inline-block; width: 180px; height: 20px; position ...

When using @mouseover, it is not possible to modify a variable's value

The hover event is not functioning properly in this Vue component. Although I was able to call a function on hover successfully, I encountered issues when trying to change the hover variable directly. <template> <div @mouseover="hover = t ...

Manipulating Arrays in JavaScript: Techniques for Extracting Values Buried in Nested Objects

I am working with an array of objects that contain multiple "Book" objects with dynamic keys. My goal is to filter the objects in the array to only include those that have at least one new "Book" object. For example: const arr = [ { id: '123&ap ...

encountered an issue when attempting to execute the command "vue create app1"

Whenever I attempt to run a command in the CLI, I encounter the following error: vue : File C:\Users\john\AppData\Roaming\npm\vue.ps1 cannot be loaded because scripts are disabled on this system. To learn more, please visit ...

Error: ng-messages syntax issue with the field parameter

Encountering the following error: Syntax Error: Token '{' invalid key at column 2 of the expression [{{field}}.$error] starting at [{field}}.$error]. when attempting to execute the code below (form-field.html) <div class='row form-grou ...

I keep getting an error saying "wallet.connect() is not a function," even though it was working perfectly just a few

`` I'm currently working on the FCC solidity course and I've reached the 7:45 mark. Everything was running smoothly until I encrypted the RPC url, private key, and password. Now, when trying to connect my wallet variable to the provider variable ...

Avoid duplication of elements in Angular applications

Currently, I have a component that loads animated divs based on a datasource. *Note: In the example, I've used a lot of <any> because I haven't finalized the model yet. apiService.ts dataArray: Observable<Array<any>>; constru ...

Modifying the maximum value of a number field attribute in jQuery after a successful action

As I continue to learn jQuery, I encountered a situation with the following form: <form class="simple-checkout" enctype="multipart/form-data" method="POST" action="<?php echo admin_url('admin-ajax.php'); ?>"> <input type="hidd ...

Errors arise in VUEJS when using forEach on arrays due to "this"

I can't seem to figure out why my code is no longer working, even though it was functioning perfectly fine before. Essentially, what I am trying to do here is fetch posts using axios from my database and then add those posts to an array. This is how I ...

Encountering an issue while attempting to generate a dialog popup with jQuery

As a beginner in jQuery, I am attempting to implement a popup dialog box for users in case of an error. However, I'm encountering issues with the following jQuery code: <script type="text/javascript"> $(document).ready(function() { var $dia ...

The Hidden Power of jQuery: Unleashing the Full Potential of .text()

I'm trying to make two values equal, but it's not working... var rowID = $("#@idSelectObjectGuid").val(); $($(".ls-grid-body tr").children("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="240a64524770454648410a74564d ...

How to Extract a Link from JSON Data in React Native

My JSON data is formatted like this: orderData:"<p>Key VVV: 6326233</p> <p>Download link <a title=\"Movie\" href=\"https://play.google.com/store/movies/details/The_Angry_Birds_Movie_2?id=O_RbjOHHpIs&hl=en\" t ...

Symfony: Enhancing array elements with updated bootstrap progress bar

I'm facing a challenging issue that I need help with. Currently, I have a command set up to send a large number of emails (around 300 or more) every 5 minutes using cron in order to distribute a newsletter. My goal is to keep track of how many emails ...

"Implementing a full page refresh when interacting with a map using

Here is an example of how I display a map on the entire page: <div id="map_canvas"> </div> UPDATE 2: I have successfully displayed a menu on the map, but there is a problem. When I click on the button, the menu appears briefly and then disapp ...

Use an if-else statement in jQuery with selectors to determine if a specific div element has been added to it

What if you have a main div and append one of these sub-divs to it? For example: <div class ="append"> <div id ="one"></div> <div id ="two"></div> </div> Then in jQuery, could you do something like this: if ($(.a ...

I am attempting to establish a connection with the Converge Pro 2 system from Clearone using NodeJS node-telnet-client, but unfortunately, my efforts to connect have been unsuccessful

My connection settings are as follows: { host: '192.168.10.28', port: 23, shellPrompt: '=>', timeout: 1500, loginPrompt: '/Username[: ]*$/i', passwordPrompt: '/Password: /i', username: 'clearone ...

Error: TypeScript Knockout table failing to display data

I have a table that displays invoices, along with a nested table showing the individual checks associated with each invoice. I am using knockout and typescript to render these tables. Currently, I can successfully display the invoices but am facing difficu ...

The Jquery Index() method often results in a return value of -

I have developed a function in JavaScript that creates HTML content. Within the test(test1) function, I am checking if test1.Test__c is null and changing the color accordingly. The line ".table-striped > tbody > tr.testcss" is responsible for changin ...

A PHP tag containing a div element

As someone who is new to web development, I have a question that may seem silly to some. I am familiar with adding div tags inside php tags, but I am unsure if it's possible to add onclick functions or any other type of function to these div tags. He ...