Listening for Events from Child Components in Vue.js

I am struggling to figure out how to send an event from a child component to its parent in order to change the view.

Although I have been able to create and emit the event, my template does not seem to be properly registering it. I am working with Single File Components (SFC). Additionally, if I manually update the data object, everything works as expected.

In App.vue (Parent):

<template>
    <div v-on:change-view="updateView">
        <!-- Render the currently active component/page here -->
        <component v-bind:is="currentView"></component>
    </div>
</template>
<script>
export default {
  name : 'app',
  data () {
      return {
          currentView : 'Modal'
      }
  },
  methods : {
      updateView (view) {
          console.log('Event listener triggered!')
          this.currentView = view;
      }
  }
}
</script>

In Modal.vue (Child):

<template>
    <div> 
        <vk-modal v-bind:show="show">
            <h1>{{ title }}</h1>
            <p>{{ body }}</p>
            <p class="uk-text-right">
                <vk-button v-on:click="$emit('change-view', 'Purposes')">More Information</vk-button>
                <vk-button v-on:click="fullConsent" type="primary">I Agree</vk-button>
            </p>
        </vk-modal> 
    </div>
</template>
<script>
export default {
  name : 'modal',
  data () {
      return {
          show : true,
          title : 'Hello'
      }
  },
  methods : {
        fullConsent () {
            this.show = false;
        }
  }
}
</script>

If anyone could provide some assistance, that would be greatly appreciated! :)

Answer №1

To ensure the event listener is properly registered, it must be assigned to the <component> itself as component events do not propagate like DOM events (in contrast to DOM events).

<div>
    <component v-bind:is="currentView" v-on:change-view="updateView"></component>
</div>

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

Looking to spice up your static HTML site? Dive into the world of Ruby on

I recently developed an app that features a static HTML webpage containing text and images, and now I'm interested in incorporating Ruby on Rails to explore its capabilities further. After creating a basic RoR application, I copied the HTML content f ...

Google Interview Challenge: Finding Pairs that Sum Up

My approach to solving this problem involved iterating through the array and checking if there exists an item such that the sum equals array[i] + item. If such a pair is found, I return true; otherwise, I return false. Now, my main inquiry is: How can I m ...

Accessing Data from Nested PHP Array in Javascript

My current situation is this: I have a MYSQL database that consists of two fields: 'ID' and 'string'. The 'string' field stores serialized arrays. To extract the data back, I utilize the following PHP code: $result = mysql_q ...

Creating a variable by utilizing $index values within two nested v-for loops

For my project, I am attempting to organize the days of a month into a table using 2 v-for loops. To simplify my code, I am considering creating a t_index variable that would be equal to ((r_index - 1) * 7 + c_index) - 2, but I am unsure how to implement ...

How can I change the background color of my notification box to red if the count is not equal to zero?

When the count equals 0, I don't want any effect on the notification box. However, when the count is not equal to zero, I want the notification box to turn red. I tried implementing this, but it's not working as expected. By not working, I mean n ...

The fetch() POST request is met with an error message stating "415 Unsupported Media Type"

I keep encountering a 415 error when attempting to upload a PDF file using fetch(). The PDF file resides in the same directory as the js file, and the name is correct. async function uploadFile(filePath, extension, timestamp) { const url = "https ...

Position of JSON data response is inaccurate

Currently, I have a function that calls an API from the server in the following manner: getDataSet(callback) { request.open('POST', `${apiPath}`); request.setRequestHeader('Content-Type', 'application/x-ww ...

Avoid interrupting the code execution until it has finished completely

Let's discuss a common scenario: $('button').on('click',function(){ // Performing AJAX requests (which may take some time); }); If the user clicks the button multiple times, numerous ajax requests can be triggered. To prev ...

Checking the status of a checkbox after submitting using AngularJs

For my first application, I am utilizing AngularJs and JavaScript to display information from an API as checkboxes. Currently, the functionality is working well, but I am unsure how to validate if any checkbox options are checked with a submit button. Aft ...

Enable seamless SCSS inclusion in Vue components through automatic importing

My goal is to import a variables.scss file globally in my Vue project. I have set up my vue.config.js file as follows: module.exports = { css: { loaderOptions: { scss: { additionalData: `@import "@/st ...

loading times of Bootstrap-select are slow when used in multiples

I am facing performance issues on my website when I try to include more than 20 select options. The jQuery execution slows down significantly and there is a stop/continue alert, taking minutes to load. Is there any way to optimize the code for faster loadi ...

Creating multiple unique custom attributes for a specialized HTML element

Creating getter/setter methods for a custom attribute on a custom HTML element is quite simple: customElements.define('custom-el', class extends HTMLElement { static get observedAttributes() { return ['customAttr'] ...

The information retrieved from the API is not appearing as expected within the Angular 9 ABP framework

I am facing an issue with populating data in my select control, which is located in the header child component. The data comes from an API, but for some reason, it is not displaying correctly. https://i.stack.imgur.com/6JMzn.png. ngOnInit() { thi ...

Animate the div only when the button is clicked

I need a way to hide the text inside a div when it exceeds a certain height, but then expand it to full height upon clicking a button. However, I want this action to only affect the parent div of that specific button, rather than all the divs on the page. ...

Arrange a div element within another div by utilizing the fixed positioning property, while also accounting for any potential "white space

Can someone help me figure this out: I currently have this much progress: http://jsbin.com/apikiw/3/edit#preview The issue I'm facing is that I am unable to insert it between the <p /> tags due to its dynamic nature... any solutions or suggest ...

Leveraging server-side data with jQuery

When my client side JQuery receives an array of JSON called crude, I intend to access and use it in the following way: script. jQuery(function ($) { var x = 0; alert(!{JSON.stringify(crude[x])}); ...

Sending information to a Flask application using AJAX

Currently, I am working on transferring URLs from an extension to a Flask app. The extension is able to access the current URL of the website. I have set up an AJAX request to connect to Flask, and the connection is successful. However, when trying to send ...

Update the color of the text depending on the background color

When hovering over my CTA, a sliding effect occurs. However, I am facing an issue with the text being difficult to read depending on the background color. To better understand what I'm trying to achieve, you can view the demo here: Demo on CodePen T ...

How can I verify if a date is after the current date using Node.js?

I am struggling to set up date validation that ensures the date is after the current date. This is what I have attempted so far: Router.post('/home', [ check('due_date') .isDate() .isAfter(new Date.now()) .wi ...

Substitute placeholders in array with information using a loop

I have a question regarding implementing an autosort feature in JavaScript. I want my page to automatically sort data rows based on different time intervals selected by the user through checkboxes. The data updates every 3 seconds, and the autosort functio ...