"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.

https://i.sstatic.net/xGJRP.png

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

The system encountered an error due to the absence of a defined Google or a MissingKeyMapError from the

Currently, I am developing a component that includes ng-map functionality by following the guidance in this tutorial. <div class="content-pane" map-lazy-load="https://maps.google.com/maps/api/js" map-lazy-load-params="{{$ctrl.googleMapsUrl}}"> & ...

Excluding specific e2e tests in Protractor: A guide

I have a collection of end-to-end tests for my AngularJS web application. Here is the configuration in my current protractor.config.js file: // __dirname fetches the path of this specific config file // assuming that the protractor.conf.js is located at t ...

What is the process for adding elements to the parent elements that have been selected using getElementsByClassName?

Here is the JSP code snippet I'm working with: <% while(resultSet1.next()){ out.println("<p class='comm'>"); out.println(resultSet1.getString("answer_content")); ...

JavaScript Promise Fundamentals

While I am quite familiar with coding in JavaScript, the benefits of promises in the JS world still seem somewhat unclear to me. Below is an example of asynchronous calls using callbacks nested within each other. (function doWorkOldSchool() { setTime ...

Currently, I am utilizing Angular 2 to extract the name of a restaurant from a drop-down menu as soon as I input at least two characters

I am currently utilizing Angular 2 and I am trying to retrieve the names of all restaurants from a dropdown menu. Currently, when I click on the text field, it displays all the results, but I would like it to only show results after I have entered at least ...

Sharing session data between controller and view in an Express.js application

When logging in with the code below in the express controller to redirect to the main page: req.session.user = user.userLogin; if (req.session.user=='Admin') { global.loggedAdmin = user.userLogin; } else { global.loggedUser = user.us ...

What is a more definitive way to define a variable other than using const?

One of my components, called NoteComponent, emits a message called note-not-saved. To handle this message, I have the following code: <template> (...) <NoteComponent @note-not-saved='() => noteNotSaved=true' /> (...) </templ ...

Utilizing an Immediate-Invoked Function Expression (IIFE) for jQuery in JavaScript

I'm looking at this code snippet that I believe is an Immediately Invoked Function Expression (IIFE). But, I'm confused about the role of (jQuery) and ($). I understand that it involves passing a reference to jQuery into the IIFE, but can someone ...

Retrieving Data from Repeated Component in Angular 6

Need Help with Reading Values from Repeating Control in Angular 6 I am struggling to retrieve the value of a form field in the TS file. Can someone please assist me with this? This section contains repeating blocks where you can click "add" and it will g ...

Exploring JSON Parsing in JavaScript

Upon processing the following JSON data: foobar({ "kind": "youtube#searchListResponse", "etag": "\"I_8xdZu766_FSaexEaDXTIfEWc0/pHRM7wJ9wmWClTcY53S4FP4-Iho\"", "nextPageToken": "CAUQAA", "regionCode": "PL", "pageInfo": { "totalResults": 68 ...

getStaticProps will not return any data

I'm experiencing an issue with my getStaticProps where only one of the two db queries is returning correct data while the other returns null. What could be causing this problem? const Dash = (props) => { const config = props.config; useEffect(() ...

featherlight.js - Execute code when modal is triggered

Situation with HTML <div id="form-lightbox"> <div class="form"> <div id="ajaxreplace"> <script type="text/javascript"> jQuery(function() { jQuery.ajaxReplace({ //parame ...

Is there a way for me to confirm if a node module is compatible with bundling in Webpack and running in a web browser?

One of the advantages of using Webpack is its ability to bundle up node modules for use in an HTML page within a browser. However, not all node modules are compatible for this purpose. Certain modules, such as those utilizing the 'fs' module or n ...

In strict mode, duplicate data properties are not allowed in object literals when using grunt-connect-proxy

I recently started following a tutorial on AngularJS titled "Hands on Angularjs" by Tutsplus. In the tutorial, the instructor uses the grunt-connect-proxy package to redirect ajax requests to a Rails server running on localhost:3000. However, I believe the ...

What is preventing the content from appearing beside the v-navigation-drawer component?

I am having some trouble setting up a navigation drawer on the left with content on the right. I'm using a template called from a router-view, but for some reason, the "Content here" section is not showing up at all. It seems like it doesn't even ...

Is there a way to access the element reference of a component directly within the template?

When I mouse over certain elements, I use the following code to set focus: <div #divTemplateVar (mouseover)="divTemplateVar.focus()"></div> However, this method does not work for components: <component #componentTemplateVar (mouseover)="c ...

Troubleshooting an issue with importing a Component in ReactJS using material-ui

Using the material-ui library, I attempted to create a Table following the code provided in the Custom Table Pagination Action example. However, I encountered the following error: Error Encountered: Warning: React.createElement: type is invalid -- expect ...

Acquiring an alternative data structure in JavaScript or JSON

When clicking on a div with different attributes, I am attempting to retrieve a data object. Here is an example: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var locA = { "fro ...

Is it possible to invoke this JavaScript function like this?

Is there a way to call a function like item_edit.say hello by passing it as a string on the window object (similar to the last line in the snippet below)? var arc={ view: { item_edit: {} } }; arc.view.item_edit={ say_hello: function(){ alert(' ...

inSession variable in express: set to false

i keep receiving inSession:false when attempting to log in, it is expected to return true. I am utilizing express session, in combination with postges and sequalize. I have logged the state values and they are being rendered correctly, so they are n ...