Passing an object to child components in Vue JS after they have been successfully mounted

My situation involves three Vue components. The first component is a page listing, which contains a filter and a list. As the page listing component renders, it needs to parse JSON and pass that object into the filter component. However, I'm facing an issue where the mounted script runs after the filter component has been rendered, resulting in no object being passed to the filter for rendering. How can I work around this problem? I've looked into the Vue lifecycle but am unable to pinpoint the exact issue.

In the filter component, when I output {{test}}, it displays the correct text 'yayaya' because it's a string and doesn't require manipulation. But why does {{dataTagGroups}} in the filter component return nothing; it appears empty?

LISTING PAGE COMPONENT

<template>
<div>
    <section class="mega-filter js-mega-filter">

        <mega-filter
            :dataEndpoint="dataEndpoint"
            :dataTagGroups='dataTagGroups'
            :dataSortOptions='dataSortOptions'
            test="yayaya"
            v-cloak
        >
            <!-- label for sort filter -->
            <template slot="sortLabel">Sort</template>
            <template slot="sortLabelMobile">Sort by</template>
        </mega-filter>

   
    </section>
    </div>
</template>

<script>
    import listingcards from '../listing-cards/_listing-cards.vue';
    import megafilter from '../megaFilter/_mega-filter.vue';
    import axios from 'axios';
    export default {
        name: 'listing-cards-list',
        components: {
        'mega-filter': megafilter
        },
        data() {
            return {
                dataEndpoint: '',
                dataTagGroups: {},
                dataSortOptions: {},
                dataNumItems: '',
                dataPageSize: ''
                
            };
        },
        props: {
           
        },
        directives: {
            
        },
        methods: {
           
        },
        mounted() {
            
            
                this.dataEndpoint = this.$el.attributes['data-endpoint-url'] ? this.$el.attributes['data-endpoint-url'].value : null;
            console.log(this.dataEndpoint)
                // set tagGroups options
                const tagGroups = this.$el.attributes['data-tag-options'] ? this.$el.attributes['data-tag-options'].value : null;
                if (tagGroups) {
                    try {
                        this.dataTagGroups = JSON.parse(tagGroups)['tagGroups'];
                    } catch(err) {
                        console.error('Error parsing sort options');
                    }
                }
                console.log(this.dataTagGroups)
                // set sort options
                const sortOptions = this.$el.attributes['data-sort-options'] ? this.$el.attributes['data-sort-options'].value : null;
                if (sortOptions) {
                    try {
                        this.dataSortOptions = JSON.parse(sortOptions)['sortOptions'];
                    } catch(err) {
                        console.error('Error parsing sort options');
                    }
                }
                 console.log(this.dataSortOptions)

            
        }
    }
</script>

FILTER COMPONENT

<template>
    <div class="mega-filter__container l-padding">

        {{dataEndpoint}}
 
    </div>  
</template>

<script>
import { mixin as clickedOutsideDrawer } from 'vue-on-click-outside';
import axios from 'axios';


export default {
    name: 'mega-filter',
    data() {
        return {
            
            dataNumItems: '',
            dataPageSize: '',
            tagFilters: [],
            sortByFilters: [],
            
            url: '',
            ...CONFIG
        }
    },

    props: {
          dataEndpoint: '',
            dataTagGroups: {},
            dataSortOptions: {},
            test:''
    },

    mounted() {
       
    },
    methods: {
      
    }
}
</script>

Answer №1

To begin with, you can initialize the dataTagGroups and dataSortOptions in your data as null and only present the filter if they are no longer null.

 data() {
   return {
    dataEndpoint: '',
    dataTagGroups: null,
    dataSortOptions: null,
    dataNumItems: '',
    dataPageSize: ''
 },

In your template, use v-if to conditionally render the filter based on those criteria being met.

<section class="mega-filter js-mega-filter">
  <mega-filter
    v-if="dataEndpoint && dataTagGroups"
    :dataEndpoint="dataEndpoint"
    :dataTagGroups='dataTagGroups'
    data-tag-name=""
    :dataSortOptions='dataSortOptions'
    data-sort-name=""
    data-sort-direction-name=""
    data-sort-direction-value=""
    data-facet-options=""
    data-num-items="10"
    data-page-size="5"
    data-language=""
    test="yayaya"
    v-cloak
  >
    <!-- label for sort filter -->
    <template slot="sortLabel">Sort</template>
    <template slot="sortLabelMobile">Sort by</template>
  </mega-filter>
  <div v-else>
    Data not ready yet... Loading...
  </div>
</section>

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 Looping through multiple files for upload will return the last file in the series

I'm currently working on implementing a multiple file upload feature using JavaScript. Within my HTML, I have the following input: <input type="file" (change)="fileChange($event,showFileNames)" multiple /> When the onChange event is triggere ...

What is the process of combining two identical objects in Angular JS?

Is it possible to merge and sort two objects in Angular JS that have the same fields, notifications.fb and notifications.tw, based on their time field? ...

Navigating through different sections of your Angular app can be easily accomplished using

My current project structure is set up like this: The application I am working on is hosted in a subdirectory called /my-scripts/vk.plants. This means that when I request this URL, it loads layout.html and returns it to the user. layout.html contains the ...

AngularJs: Issue encountered while compiling an ng-switch statement

Programming <input type="text" ng-model="user.name" /> <div ng-switch on="user.name"></div> <p ng-switch-default>The winner is</p> <h1 ng-switch-when="John">{{ user.name }}</h1> Can anyone help me? I encountered ...

No specification has been provided for the delivery

I'm currently working with the Meteor framework and I am attempting to send an uploaded file (HTML input) from the client to the server using the npm package Delivery. Below is my code: Client side : var socket = io.connect('http://0.0.0.0 ...

Converting JSON to JavaScript Date using UTC time

I am struggling with formatting the dates in a JSON object to work with highcharts. The JSON looks like this: [ [ "26-Sep-14", 10 ], [ "29-Sep-14", 75 ] ] Highcharts requires dates to be in the format Date. ...

Combine information within a designated column

I am facing an issue with the table structure below: <table class="table main-table" ng-if="linesArray && linesArray.length > 0"> <!-- HEADER--> <thead class="table-head"> <tr> <th ng-repea ...

The constant issue persists with the NuxtJS store state variables continuously coming back as

I am facing an issue with the NuxtJs store where it keeps returning undefined. Even after looking at multiple similar questions, I haven't been able to find a solution. Here is my code snippet: import Vue from 'vue' import Vuex from 'vu ...

Exploring FabricJs: Reassessing the coordinates of an object post-rotation

const canvas = new fabric.Canvas("c", { selection: false }); const refRect = new fabric.Rect({ left: 250, top: 150, width: 200, height: 100, fill: 'transparent', stroke: 'blue', originX: 'center', originY: & ...

Import .vue single file component into PHP application

I've been struggling to integrate a .vue single file component into my php app without using the inline template method. Since I don't have a node main.js file to import Vue and require the components, I'm not sure how to properly register m ...

Why am I experiencing a 300% decrease in speed with SSR on Nuxt compared to CSR?

Currently, I am developing a website that showcases market data for over 500 items in a video game. When using the Vue application, transitioning to the market page was almost instantaneous and functioned flawlessly. However, I decided to switch the projec ...

Concealing an item in an Angular Ionic repeater

I am creating a customizable list control where users can filter through different data levels. This list control consists of 4 hierarchical levels with numerous items. Initially, only the first level item is displayed. Upon clicking on the first level, th ...

Attempt to efficiently register components automatically on a global scale in Vue by utilizing the powerful combination of Laravel-Mix and Webpack

In my previous projects with Vue, which were based in a Laravel-Mix/Webpack runtime environment, I used to individually register components and views as needed. This was done by importing them and extending Vue: import BaseButton from './components/Ba ...

Understanding how to retrieve the value count by comparing strings in JavaScript

In my array object, I am comparing each string and incrementing the value if one letter does not match. If three characters match with the string, then I increase the count value; otherwise, it remains 0. var obj = ["race", "sack", &qu ...

Is it possible for a submission of a form to modify the content length header, resulting in the request failing?

Issue Description: After binding a submit event to an AJAX post request in order to send a predetermined key-value pair to a PHP script, the expected message indicating successful communication is not received. Despite the fact that the submit event trig ...

Working with Angular to add various items to an array based on multiple conditions

Currently, I am a beginner in TypeScript and currently involved in an Angular project. As part of my work, I need to make an API call and perform various operations on the received data: public data_Config: IConfig[] = []; this.getService.Data(input).sub ...

What is the best way to divide the Jquery.js file into smaller, separate files?

My web server has a strict file size limit of 64KB and I heavily rely on jQuery for my project. Unfortunately, using any other library like zepto is not an option. The minified size of jQuery alone is 95KB, so I need to split it into two smaller files. C ...

What is the correct way to use Deviceready in an Ionic application?

I am currently working on a mobile application built with Cordova and Ionic. The default page of the application requires the use of the SQLLite plugin. https://github.com/brodysoft/Cordova-SQLitePlugin The issue I am facing is that the view contains n ...

What is the reason for jQuery's ajax feature running scripts by itself?

Lately, I've observed an issue where jQuery functions seem to disappear if a jQuery ajax call is made immediately after injecting jQuery into an inner iframe. The functions like `.dialog()`, `.draggable()`, and other plugins stop working when the ajax ...

The run() function in AngularJS inside an IFrame does not execute again when the IFrame is reloaded

In my webpage, there is a "Start Portal" button and an iframe with the id: MyFrame. Both elements are on the same webpage. I use jQuery AJAX to fetch the URL of my AngularJS based portal and then set this URL as the src for the iframe. The code snippet be ...