Invoke a parent method from a nested child component in Vue

After setting up a project with vue-cli using the webpack template, I decided to incorporate a reusable bootstrap modal dialog in the App component. To achieve this, I created a method called showMessage in the App component that handles displaying the modal.

With the requirement of being able to access this method from any component in mind, I started exploring different ways to call it. One approach I came across was shown below:

this.$root.$children[0].showMessage('Message', `An email will be sent to ${this.form.email}`)

Answer №1

Dealing with global messaging in a delicate manner is crucial.

To ensure proper handling, consider setting up an event listener on the root component from within the modal component:

methods: {
  showMessage(message) {
    // your code to display the message
  }
},
created() {
  this.$root.$on('showMessage', this.showMessage)
},
destroyed() {
  this.$root.$off('showMessage', this.showMessage)
}

You can then use

this.$root.$emit('showMessage', 'foo message')
to show a message from anywhere within the root component's scope.


Alternatively, you could create an event bus:

Vue.prototype.$bus = new Vue();

methods: {
  showMessage(message) {
    // your code to display the message
  }
},
created() {
  this.$bus.$on('showMessage', this.showMessage)
},
destroyed() {
  this.$bus.$off('showMessage', this.showMessage)
}

this.$bus.$emit('showMessage', 'foo message')

This approach offers a slightly improved separation of concerns.

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

When the browser back button is clicked, conceal the current div and reveal the previously hidden div

I'm faced with a situation where my website consists of multiple pages which I've achieved by displaying and hiding divs within a single html file. The issue I'm encountering is that the browser's back and forward buttons aren't fu ...

Adding elements to a JSON array in Javascript

Seeking assistance on updating a JSON array. var updatedData = { updatedValues: [{a:0,b:0}]}; updatedData.updatedValues.push({c:0}); This will result in: {updatedValues: [{a: 0, b: 0}, {c: 0}]} How can I modify the code so that "c" becomes part of ...

Select2.js Dropdown List with Case Sensitivity

Currently making use of select2.js version 4.0.3 Situation: Imagine the dropdown list contains the following options: JavaScript javascript Javascript javaScript So, when a user types in java, all options are displayed (case is n ...

Troubleshooting event binding problems with jQuery

<div id="parent"> <div id="children"> </div> </div> If we attach the same events to both parent and children elements: $("#parent").live({ mouseenter : Infocus , mouseleave : Outfocus }); $("#childre ...

Updating the background color using typescript

Before transitioning to angular development, I had experience working with vanilla Javascript. I encountered a challenge when trying to modify the css properties of specific elements using Typescript. Unfortunately, the traditional approach used in Javascr ...

Extension: What is the best way to leverage data obtained from an ajax request in order to dynamically modify an already existing element within

I've been trying to find a reliable and comprehensive tutorial for JavaScript (JS) and Ajax, but so far my search has been futile. Unlike Python.org for Python or php.net for PHP, I haven't found a satisfactory resource yet. Any recommendations w ...

When using Mongoose with Ejs, I am unable to view the comment I made when I navigate back to the post using GET. The comment only becomes visible after I have submitted it

After creating a comment, I can only see it when rendering the same page again. However, if I navigate to posts or myposts page and then return to the post where I created the comment, it disappears. Can someone please help me understand why this is happen ...

An issue has occurred: TypeError - It is impossible to access the 'forEach' property of an undefined object

Having trouble with a promise issue that I just can't seem to solve. Whenever I enter 'pizza' into the search bar and click search, the console displays an error message: TypeError: Cannot read property 'forEach' of undefined I&ap ...

Tips on deleting CSS comments from a CSS file

Currently, I am utilizing nextjs + reactjs. My objective is to eliminate all CSS comments from my existing css file. Despite using next-purgecss in order to get rid of unnecessary CSS code, the comments are still persisting. What could be the reason behind ...

Node.js Express not inserting data with Mongoose when using form data

For the past two weeks, I have been struggling to post data to insert into a database using form-data. It consistently shows a 400 bad request error. Below is my code for server.js: require('./db.js') let express = require('express') ...

Easily fetching data with AJAX through jQuery

Completely new to using jQuery and AJAX, I attempted the code below for a simple http get request: <html> <head> </head> <body> <script src = "jquery-2.1.4.js"></script> <script src = "app.js"></script& ...

What is the best way to include default text in my HTML input text field?

Is it possible to include uneditable default text within an HTML input field? https://i.stack.imgur.com/eklro.png Below is the current snippet of my HTML code: <input type="text" class="form-control input-sm" name="guardian_officeno" placeholder="Off ...

deliver a promise with a function's value

I have created a function to convert a file to base64 for displaying the file. ConvertFileToAddress(event): string { let localAddress: any; const reader = new FileReader(); reader.readAsDataURL(event.target['files'][0]); reader ...

The issue of `Console.log` displaying as undefined arises after subscribing to a provider in Ionic3

In the process of implementing the Spotify api into my Ionic 3 app, I encountered an issue where the data retrieved appears as undefined when attempting to log it. Let me share some code and delve deeper into the problem. Here is the function getData() tha ...

What is the best way to determine if a radio button has been chosen, and proceed to the next radio button to display varied information?

The goal is to display the <div class="resp"> below each radio button when it is selected, with different content in each <div class="resp">. The previously selected <div class="resp"> should be hidden when a new radio button is chosen. O ...

strategies for chaining together multiple observables with varying data types and operations

Hey everyone! I'm facing a situation where I have a form with multiple select types, and the options for these inputs are coming from an API. I then take the data emitted from the HTTP request observable and feed it into my FormGroup, and everything i ...

The AngularJS HTTP interceptor is a crucial component for handling

Is there a way to use an interceptor in AngularJS to log "finished AJAX request" when any request is completed? I've been exploring interceptors and currently have the following setup, but it triggers at the beginning of the request rather than the e ...

Passing props from pages to components in NextJS: A guide

My nextjs-application has a unique folder structure: components -- layouts --- header.tsx --- index.tsx pages -- index.tsx -- [slug].tsx In the [slug].tsx file, I utilize graphql to fetch data and set the props accordingly: export default ...

Why doesn't express.js throw an error when the variable 'app' is used within its own definition?

When working with express.js, I find it puzzling that createApplication() does not throw an error. This is because it uses app.handle(...) within an anonymous function that defines the same variable 'app'. I attempted to replicate this in jsFidd ...

Locate and substitute `?php` and `?` in a given string

I am facing a challenge with inserting a large string of valid HTML code into the DOM, as the string also includes PHP code. When Chrome renders the code, it automatically comments out the PHP sections. The PHP code is encapsulated in <?php ... ?>, s ...