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

Leveraging v-model to connect user input with the state stored in Vuex

I'm currently working on a project that involves the following components: //store.js import modulePaciente from './paciente/modulePaciente' export default new Vuex.Store({ getters, mutations, state, actions, modules: { ...

I have expanded the CSSStyleDeclaration prototype, how do I access the 'parent' property?

I have developed some custom methods for CSSStyleDeclaration and implement them like this: A_OBJECT.style.method() ; The code structure is quite simple: CSSStyleDeclaration.prototype.method = function () { x = this.left; ..... etc } Here's my que ...

Connect the Vue component to the Vue instance

I am currently working with a Vue component that looks like this: Vue.component('number-input', { props: {}, template: `<textarea class="handsontableInput subtxt area-custom text-center text-bold" v-model="displayValue" @blur="isInput ...

Struggling to Convert Array of MongoDB Documents from Backend into React Components

In an attempt to connect my front-end to the back-end, I am looking to retrieve all the "blog posts" stored in my MongoDB database. Currently, there is only one document available for testing purposes. The backend contains this API endpoint: app.get("/api ...

Ensure that the three.js script remains in a fixed position on a page that can be

Is there a way to make a 3D model created with three.js have a fixed position on a scrollable page, like a background while the rest of the content scrolls normally? Are there any CSS techniques or additional script elements that can be used to achieve thi ...

Enhance the Vue.js performance by preloading components

After discovering the benefits of lazy loading components, I decided to start implementing it in my project. However, I encountered some issues when trying to prefetch the lazy loaded components and vue-router routes. Upon inspecting with Chrome DevTools, ...

Electron and React: Alert - Exceeded MaxListenersWarning: Potential memory leak detected in EventEmitter. [EventEmitter] has 21 updateDeviceList listeners added to it

I've been tirelessly searching to understand the root cause of this issue, and I believe I'm getting closer to unraveling the mystery. My method involves using USB detection to track the connection of USB devices: usbDetect.on('add', () ...

Error 500 on Firebase: Issue solving "firebase" in "firebase.js" not resolved

Struggling to incorporate Firebase into my latest React project, I keep encountering the dreaded "The development server returned response error code: 500." Despite creating a firebase.js file to house my Firebase configuration details, I am at a loss as ...

Monitor the $scope within a factory by utilizing the $http service in AngularJS

I'm attempting to monitor a change in value retrieved from a factory using $http. Below is my factory, which simply retrieves a list of videos from the backend: app.factory('videoHttpService', ['$http', function ($http) { var ...

In Javascript, you can enhance your axes on a graph by adding labels at both the

Is there a way to add labels at the beginning and end of the axes to indicate the importance level, such as "not very important" and "very important"? I am currently utilizing a slider program from here. Since I am new to JavaScript, I would greatly appre ...

Is there a way to pass around jest mocks across numerous tests?

In my test scenarios, I've created a mock version of the aws-sdk, which is functioning perfectly: jest.mock("aws-sdk", () => { return { Credentials: jest.fn().mockImplementation(() => ({})), Config: jest.fn().mockImplementati ...

Employing an object from a distinct module

After creating a function to parse objects and provide getters, I encountered an issue. I need to access this object from a different module without re-parsing it each time. Is there a way to achieve this without using a global variable? var ymlParser = r ...

HighStock chart malfunctioning with inaccurate epoch datetime display

I am working on a project that involves creating a dynamic Highstock chart to showcase the daily influx of emails. The data is stored in a JSON file that gets updated every day, and you can see a snippet of it below: [{ "name": "Month", "data": [147199320 ...

What is the best way to conceal the header on a 404 error page?

<HeaderContainer> <Switch> <Route exact path='/counters' component={ParentCounterContainer}/> <Route exact path='/about' component={AboutContainer} /> <Route exact path='/' component={H ...

Crafting a personalized arrow for sorting headers in Angular Material

Currently working on an Angular 5 project and I'm looking to implement a custom sort icon in the header. The goal is to achieve a similar effect to this example, without using the default arrow. I attempted to modify the CSS styles, but it wasn' ...

State of loading getServerSideProps in Next.js

Can we implement a loading state similar to when retrieving data on the client-side? I'm interested in having a loading state, maybe with a loading-skeleton like react-loading-skeleton On the client-side, we can achieve this by: import useSWR from & ...

Configuring Dialog Placement to the Top in Material-UI

I'm in the process of creating a popup dialog, but I'm encountering an issue where the dialog pops up in the center of the page. How can I position it at the very top of the page when the popup button is clicked? Below is the code snippet: < ...

Application route is failing to direct to the HTML page

On my MEAN stack website, I am trying to make the browser navigate to a file named 'findCable.html' but it keeps directing to 'singleCable.html'. I have double-checked the angular routing file and backend routes, but can't see ...

What is the best way to make a Dojo TitlePane overlap using CSS?

My dilemma involves a jsfiddle featuring two TitlePane widgets in the central pane's top right corner. Currently, clicking on the right TitlePane ("Switch Basemap") moves the left TitlePane ("Map Overlays") to the left. What I want is for the right Ti ...

Ways to conceal CSS on the page when triggering a different element

I am trying to achieve the functionality of hiding the black arrow when clicking on the green arrow, all without using jQuery. Here is my fiddle: http://jsfiddle.net/t5Nf8/195/ html: <div class="arrow-down"></div> <div class="arrow-up"> ...