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

Validate the error value of the confirmation message box

I wrote a script to create a confirmation popup window. However, when I implement it in our aspx.cs page, it seems to be returning incorrect values. Here is my script: <script type="text/javascript"> function Confirm() { var confirm_value = docu ...

Applying CSS styles to a page depending on certain conditions

Currently, I have a page in SharePoint that can function as a pop-up. I am using JavaScript to identify whether it is a pop-up by checking if window.location.search.match("[?&]IsDlg=1"). However, I am struggling to figure out how to insert CSS based on ...

Having trouble with React Testing Library throwing an error every time I try to use fireEvent on an input text?

When attempting to utilize the "fireEvent" method from React Testing Library, I encountered an error as shown below: MainSection.test.js: test('Verifying SearchBar functionality', async () => { render(<SearchBar />); const text ...

Utilizing Async / Await in the created lifecycle hook - Vue2

I recently installed the vue-element-loading package and added its component to my page.vue: <vue-element-loading :active="isActive" :is-full-screen="true"/> After adding a variable to my data: data () { return { isActive: false, } } I th ...

The error message states: "An attempt was made to destructure a non-iterable object. In order for non-array objects to be iterable, they must have a [Symbol.iterator

I need to call a RTK query endpoint from a function const [getCityCode, { isLoading, error, data, isSuccess, isError }] = useLocationQuery(); const getLocationDetails = async () => { const queryItems = { latitude: lat, longitude: long }; await getC ...

Navigating to the next page in Angular JS by clicking "Save and Next" which

Hey there, I'm currently diving into Angular JS and working on a CMS system with it. Right now, we're dealing with around 30 to 40 Objects that we load into a list. Whenever one of these objects is clicked, a Modal Window pops up using the Modal ...

Refresh Entity with Real-Time Data on Cesium

I have been attempting to showcase an entity moving within Cesium through the use of live/dynamic data. After trying various techniques and consulting past forums, particularly those from 2015-2016, I am still struggling to make it work. Despite my effort ...

Utilize a fluid AJAX endpoint for the Vue Select2 encapsulated component

I have customized the Wrapper Component Example based on VueJS documentation by adding the AJAX data source feature. You can view my modified code here. My goal is to dynamically set the ajax url property of my select2 component, like this: <select2 :o ...

Dealing with promises in AngularJS within the ui-router configuration

Below is a snippet of my $stateProvider code: $stateProvider .state("home", { url: "/", template: "<employee-info-component user='$resolve.user'></employee-info-component>", resolve: { user: function(indiv ...

By default, the sidebar is open on desktop devices while closed on mobile devices

I am struggling to figure out how to set my sidebar/navigation content, using Bootstrap, to be expanded by default on desktop and closed by default on mobile with the icon only showing on mobile devices. Despite multiple attempts, I cannot seem to make thi ...

What is the best way to change an http call in a controller to a Service/factory pattern that accepts a parameter?

Currently, I have a controller making use of http.get, http.push and http.post methods within my AngularJS app. During my learning journey with AngularJS, I've discovered that it's more efficient to place http.get calls in service files. While I ...

Instant urban locator

Is there a way to automatically populate the visitor's city in the membership form? Member Register Form Name: Emre Email:--- Pass:--- City: Istanbul // Automatically detected location How can I implement automatic location detection for the ...

How can you achieve three layers of nested quotes in Dynamic HTML?

Working on an app that utilizes JQuery and JQTouch for iOS. The issue I'm facing involves dynamically generated HTML lists where the user clicks a row that needs to be highlighted. However, achieving this has proven tricky due to nesting 3 sets of quo ...

Tips for designing a horseshoe-inspired meter using CSS

  I want to create a horseshoe-shaped gauge using CSS that resembles the image below:     My attempt involved creating a circle and cutting off the bottom, similar to the technique demonstrated in this fiddle: http://jsfiddle.net/Fz3Ln/12/   Here& ...

InvalidType Error: The roles provided are not in the correct format, it should be a Role, Snowflake, or an Array/Collection of Roles or Snowfl

Having trouble setting up multiple select menu options on Discord.js v14. I'd like to assign more than one role to a member when multiple options are chosen in the dropdown menu. However, I'm encountering this error message: TypeError [Invalid ...

Monitoring AJAX POST progress with Node.js and Multipart: XMLHttpRequest

Is there a way to provide real-time updates on the size of a file being uploaded to a client, similar to how YouTube does it? I've looked into getting the full size of the file with req.files.myFile.size, but is there a method to track the current siz ...

Accessing instance variables from a chained observable function in Angular 2/Typescript

Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated as ...

Notification continuously appears when clicking outside of Chrome

I have implemented the use of onblur on a text box to display an alert. However, I encountered an issue where if I click outside my Chrome browser after entering text in the text box and then click on the Chrome browser button in the task bar, the alert ap ...

Ordering an array in a VUEjs template using computed properties

Working with a VUE template, I retrieve an array from an API which contains a list of countries. Now, based on the ID received, I have a requirement to rearrange this array... The code snippet may resemble something like: Vue.component('select-list ...

Tips for resolving the 'node-gyp rebuild' problem on Windows 10

While attempting to incorporate a node NPM dependency into my project, I encountered an issue with node-gyp rebuild, which I have already reported. I am aware of a potential solution from this Stack Overflow post, but unfortunately it is not effective for ...