Listening for an event triggered by a child Vue component within the same parent

My project is composed of 4 components: Header, Content, Footer, Main. Each of these components are separated into individual .vue files. Here is the code for Main.vue:

<template lang="pug">
.maincomponent
  header
  content
  footer
</template>
<script>
import Header from '@/components/Header'
import Content from '@/components/Content'
import Footer from '@/components/Footer'
export default {
  name: 'Main',
  created: function () {
    console.log('Main component created')
  },
  components: {
    'header': Header,
    'content': Content,
    'footer': Footer
  },
  data () => {
   return {
     mainData: false
   }
  }
}
</script>
<style>
</style>

Here is the code for Header.vue:

<template lang="pug">
.header {{property}}
    button(@click='buttonClick') Button
</template>
<script>
export default {
  name: 'Header',
  props: {
    property: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    buttonClick: function () {
      this.$emit('headerButtonClick')
    }
  }
}
</script>

<style>
</style>

Update: I have successfully rendered the page with this code. Now I want to emit the event buttonClick from Header -> catch it in Main -> and set the child prop 'property' to the data member 'mainData'. How can I achieve this with the current code?

Answer №1

To capture the headerButtonClick event, you need to use the directive v-on in your template code. If you're unfamiliar with the "pug" language, it would resemble something like this:

.maincomponent
header (v-on:headerButtonClick="name-of-your-main's-method")
content
footer

Once you've captured the event, you can modify the variable property in various ways. As per Vue's documentation (https://v2.vuejs.org/v2/guide/components.html#Passing-Data-with-Props), communication between parent and child components should follow these steps:

  1. The child emits an event to the parent.
  2. The parent listens for the event and takes action.
  3. The parent sets a prop for the child to access.

Therefore, the parent communicates with its child through props, while the child communicates with the parent through events.

Answer №2

When the headerButtonClick event is triggered from your Header Component, make sure to handle it within your main component like this:

<template lang="pug">
.maincomponent
  header(@headerbuttonclick='functionToExecute')
  content
  footer
</template>

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

Transforming PHP shortcode into JQuery functionality

My website is built on Wordpress, and I use javascript to load some of the content. Here's an example: jQuery(".portfolio-fs-slides").css({"display":"none"}).prepend('<div class="portfolio-fs-slide current-slide portfolio-ppreview"><d ...

Encountering an issue with eslint-loader in a new VueJS project: TypeError - eslint.CLIEngine is not recognized as

Embarking on a fresh VueJS venture with WebStorm. A brand new VueJS project has been established, NPM upgraded, Vuetify added, and upon server initiation, an error pops up: ERROR Failed to compile with 1 errors ...

How can I obtain an array using onClick action?

Can anyone help me figure out why my array onClick results are always undefined? Please let me know if the explanation is unclear and I will make necessary adjustments. Thank you! Here is the code snippet: const chartType = ["Line", "Bar", "Pie", " ...

finding the ID of the element that triggered a jQuery dialog

I'm utilizing jQuery dialog to trigger popup windows when buttons are clicked. <script> $(document).ready(function(){ $("#dialog-form").dialog({ autoOpen : false, height : 300, ...

Guide for ordering a query by the most recent updatedAt within a nested one to many relationship

I'm dealing with a set of interconnected entities structured as follows: Entity1 -> Entity2 -> Entity3 (illustrating one-to-many relationships with arrows) I am utilizing MikroORM for this purpose. Is there a way to construct a findAndCount q ...

Dynamic routing with Vue

Currently in the process of developing an application and encountering an issue with my code pertaining to dynamic routing. Utilizing Firebase to fetch data for the app, each department in the database should generate a navbar. Upon clicking on a specific ...

No data was returned after submitting the formData in the post request

Attempting to send a POST request in VueJS let data = new FormData() data.append('name', 'hey') fetch('http://homestead.test/api/customers', { method: 'POST', headers: { 'Content-type': &a ...

My Babel-Loader seems to be failing in converting the vendor code to be compatible with IE8+. What might be causing this issue?

I'm currently utilizing the most recent versions of Webpack, Babel, and Babel-Loader in my Vue.js application. My goal is to ensure that my code runs smoothly on Internet Explorer 8, 9, and 10, but unfortunately, I am facing difficulties with this. ...

Experiment with the Users.Get function available in vk-io

I am having an issue with a create command: Ban [@durov] and I encountered an error. Here is how I attempted to solve the problem: let uid = `${message.$match[1]}` let rrr = uid.includes('@') if(rrr == true){ let realid = uid.replace(/[@]/g, &ap ...

Refresh Angular component upon navigation

I have set up routes for my module: const routes: Routes = [ { path: ":level1/:level2/:level3", component: CategoriesComponent }, { path: ":level1/:level2", component: CategoriesComponent}, { path: ":level1", component: ...

Tips for displaying JSON data by formatting it into separate div elements for the result object

Having recently started using the Amadeus REST API, I've been making AJAX calls to retrieve data. However, I'm facing a challenge when it comes to representing this data in a specific format and looping through it effectively. function showdataf ...

Retrieve Browser Screen Width and Height using MVC3 Razor in the View

I am facing a challenge on my website where I need to generate a Bitmap dynamically and ensure it is rendered according to the width and height of the browser so that there are no overflow issues on the page. Although I have successfully created an image ...

The visibility of the AmCharts' OLHC chart is compromised

Here is my unique StockGraph object: "stockGraphs": [ { "id": "g5", "title": "anotherText", "precision": 4, "openField": "open2", "closeField": "close2", "highField": "high2", "lowField": "low2", ...

Mongoose fails to persist data

Exploring the world of Express and following a tutorial to create a project. Currently stuck in the seeding phase where I am trying to populate my database with data. However, when I execute the command node product-seeder.js in the terminal, no data is be ...

a guide on dynamically determining the value within a text input field

Does anyone know how to use jQuery to calculate values in a textbox for an invoice? I am not very familiar with jQuery and would appreciate any help in solving this issue. Within my invoice, there is a quantity textbox. If a user enters a quantity, th ...

Using a jQuery function to search for values in an array

This is the format of my structure: var var1 = { array1 : ['value1','value2', ...], array2 : ['value3','value4', ...] ... }; I am looking for a JavaScript function that can search for values within ...

What are the advantages of generating an HTML string on the server side and adding it to the client side?

Is there a more efficient method for transferring a large amount of data from the server to the client and dynamically generating tables, divs, and other HTML elements using JavaScript (jQuery)? Initially, I attempted to generate these elements on the cli ...

Guidelines on utilizing the information collected from social signups to seamlessly guide users towards finishing the registration process in [passport, node.js]

As a newcomer to the realm of node.js for a few months, I am still grappling with some concepts. Specifically, I need guidance on redirecting users to complete their registration using data acquired from social signups such as Facebook or Google. Current ...

Discover and eliminate the style attribute through a click action

I've been struggling to find a solution to remove the style attribute from a specific tr tag within a table when it is clicked. I've tried several lines of code but none seem to work. Here's the link to the fiddle for reference: http://jsfi ...

Listen for a click event on an Unordered List using addEventListener

Struggling to transform a for loop that iterates through an unordered list of hyperlinks and adds an 'onclick' function to each into one using an event listener instead. Unfortunately, I have not been able to create a functional solution. Below ...