"The interplay of Vue components: exploring the relationships, lifecycle hooks

Brand new to utilizing Vue.js. I am exploring the concept of having a single parent component and two child components that need to communicate asynchronously through Vue's event bus system. This involves using a dummy Vue object as a shared container for the event bus.

Here is an example setup:

EventBus.js

import Vue from "vue"
export default new Vue()

Parent.vue

import Child1 from "./Child1.vue"
import Child2 from "./Child2.vue"

export default {

    name: "Parent",

    components: {
        child1: Child1,
        child2: Child2,
    }

}

Child1.vue

import EventBus from "./EventBus"

export default {

    name: "Child1",

    beforeCreate () {

        EventBus.$once("MY_EVENT_X", async () => {
            EventBus.$emit("MY_EVENT_Y")
        })

    },

    mounted () {
        // perform some action
    }

}

Child2.vue

import EventBus from "./EventBus"

export default {

    name: "Child2",

    beforeCreate () {

        EventBus.$once("MY_EVENT_Y", async () => {
            // do something 
        })

    },

    mounted () {
        EventBus.$emit("MY_EVENT_X")
    }

}

In this scenario, my concern lies in the initialization order of the "beforeCreate" hooks compared to the "mounted" hooks within both Child1 and Child2 components in Vue. Can I guarantee that the "beforeCreate" hook will run prior to any "mounted" hook being executed?

Answer №1

Utilizing the order of component hooks between parent and children can be a powerful strategy. When the parent component's mounted hook is triggered, it ensures that all child components have been created and mounted.

Image credit: here

To implement this, you need to create a boolean flag in the parent component and set it to true within the mounted hook:

import Child1 from "./Child1.vue"
import Child2 from "./Child2.vue"

export default {

    name: "Parent",

    components: {
        child1: Child1,
        child2: Child2,
    },
    data: () => ({
      isChildMounted: false
    }),
    mounted() {
      this.isChildMounted = true
    }
}

Ensure that you pass this flag as a prop to the children components:

<child-2 :isReady="isChildMounted" />

Finally, in the child component, watch for changes in props. When the flag changes to true, all child components are ready, triggering an event emission:

import EventBus from "./EventBus"

export default {
    name: "Child2",
    props: ['isReady'],
    beforeCreate () {
      EventBus.$once("MY_EVENT_Y", async () => {
          // perform some actions 
      })
    },
    watch: {
      isReady: function (newVal) {
        if (newVal) {
          // all child components are ready
          EventBus.$emit("MY_EVENT_X")
        }
      }
    }
}

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

Troubleshooting a problem with selecting options in Jquery

Looking for assistance with a jquery script. I have a select dropdown that fetches a list of options via Ajax. When a user clicks on an option, if a certain variable equals 1, an HTML div is added. If the variable changes to another value, the HTML div dis ...

Is it possible to update JavaScript on mobile devices?

I'm currently working on a mobile site where I've implemented JavaScript to refresh a message counter. However, despite having JavaScript enabled on the device, the counter doesn't update on my Nokia e90. Interestingly, it works perfectly fi ...

Executing functions with iterations

Can anyone help me understand why my buttons always output 100 in the console log when clicked? Any ideas on how to resolve this issue? function SampleFunction(param){ console.log(param); } for (i = 0; i < 100; i++) { $("#btn-" + i).on('c ...

Creating a delay before each new object is added to an array within a loop

I have a code for loop that needs to send an AJAX request with a one second delay between each iteration. It should take the object and add it to the array using .push method. However, my current implementation only adds the first object to the array. Ca ...

Tips for positioning two elements side by side on a small screen using the Bootstrap framework

Greetings! As a beginner, I must apologize for the lack of finesse in my code. Currently, I am facing an issue with the positioning of my name (Tristen Roth) and the navbar-toggler-icon on xs viewports. They are appearing on separate lines vertically, lea ...

The functionality of two-way data binding seems to be failing when it comes to interacting with Knock

I am currently working on a piece of code that consists of two main functions. When 'Add more' is clicked, a new value is added to the observable array and a new text box is displayed on the UI. Upon clicking Save, the values in the text boxes ...

How to trigger a function in a separate component (Comp2) from the HTML of Comp1 using Angular 2

--- Component 1--------------- <div> <li><a href="#" (click)="getFactsCount()"> Instance 2 </a></li> However, the getFactsCount() function is located in another component. I am considering utilizing @output/emitter or some o ...

Having trouble configuring Angular-UI Router to work properly with Apache server

My web app is running on my PC through an Apache server, but I'm having issues with the routing provided by ui.route. It seems that the simple state I defined is never being reached. To troubleshoot, I added a wildcard to catch all paths and found th ...

Instructions on utilizing the signUp() function in Supabase for including extra user details during the registration process

My latest project involves building a Vue.js application with authentication using Supabase. I've been trying to implement the signUp() method from Supabase in order to collect extra user data during the sign-up process. In my code, I added a property ...

Make a JavaScript request for a page relative to the current page, treating the current page

When accessing the page /document/1, the request $.getJSON('./json', ... is sending a request to /document/json I'm interested in requesting /document/1/json Is there a method available to automatically resolve this path without having to ...

Getting a vnode from a DOM element in Vue 3.0: A Step-by-Step Guide

My question pertains to obtaining a vnode through accessing the DOM using document.getElementById(id). How can I accomplish this? ...

Optimal Strategies for Handling CSRF Tokens with AJAX Requests in Laravel 9 and Beyond

When working with Laravel 9+, it is crucial to expose CSRF tokens for AJAX requests in order to maintain security measures. However, the placement of these tokens can impact code organization and elegance. There are two main approaches: Approach 1: Direct ...

PHP unable to display HTML form element using its designated ID attribute

I've been experiencing some difficulties with PHP echoing a label element that contains an ID attribute within an HTML form. My intention was to utilize the ID attribute in order to avoid having to modify the JS code to use the name attribute instead. ...

CSS - using numbers to create dynamic background images

I am looking to create a design where the background images in CSS display increasing numbers per article, like this example: This idea is similar to another post on Stack Overflow discussing using text as background images for CSS. You can find it here: ...

Preserving color output while executing commands in NodeJS

My Grunt task involves shelling out via node to run "composer install". var done = this.async(); var exec = require('child_process').exec; var composer = exec( 'php bin/composer.phar install', function(error, stdout, stderr) { ...

Exploring ways to replicate the functionality of Gmail's Contact manager

Looking to develop a contact manager similar to Gmail's interface. While I have a basic understanding of AJAX and some experience with jQuery, my JavaScript skills are limited. Any suggestions for books or blogs to improve them would be welcome. Tha ...

Navigating the Foundation Topbar - Should I Toggle?

Is there a simpler way to achieve the navigation I desire, similar to the switcher for uikit? Instead of using data-toggler on each tag in my top bar, is there an easier method where I can click links in my top bar to display different content without go ...

Tips for implementing dynamic and interchangeable nested routes within Nuxt JS

In order to implement dynamic routing, the documentation suggests nesting folders with names starting with _paramname. This way, Nuxt will automatically generate routes for these dynamic subfolders. However, I am struggling to understand how to structure m ...

Error with the jQuery scrolling plugin

Currently, the script is set up this way: jQuery(document).ready(function(){ var windheight = jQuery(window).height(); var windTop = jQuery(window).scrollTop(); var windbottom = windheight + windTop ; jQuery.fn.revealOnScroll = function(){ return this.e ...

What is the best way to change a date from the format DD/MM/YYYY to YYYY-MM-DD

Is there a way to use regular expressions (regex) to convert a date string from DD/MM/YYYY format to YYYY-MM-DD format? ...