When emitting events in Vue.js, they do not automatically bubble up to higher level parent or grandparent elements

I'm trying to dispatch a custom event that will bubble up from the grandchild element through the child element to the parent element, but for some reason it's not working. Even manually triggering the event on either the parent or child element doesn't seem to have any effect.

<div id="example-app" >
   <parent>
      <child>
         <grandchild></grandchild>
      </child>
   </parent>
</div>

Check out the Component Code below:

Vue.component('parent', {
    template: ` <div @testevent="test" style="padding: 10px; background-color: red; border: 1px solid black;">
                    <button @click="$emit('testevent')">Parent Button</button>
                    <button @click="test">Trigger Test Manually</button>

                    <slot ></slot>
                </div>`,
    methods: {
        test () {
            alert('Test ok')
        }
    }
})

Vue.component('child', {
    template: ` <div style="padding: 10px; margin: 5px; background-color: green; border: 1px solid black;">
                    <button @click="$emit('testevent')">Child Button</button><br>
                    <slot></slot>
                </div>`
})

Vue.component('grandchild', {
    template: `<div style="padding:10px; margin: 5px; background-color: white; border: 1px solid black;">
                <button @click="$emit('testevent')">Grandchild Button</button>
                </div>`
})

new Vue({
    el: '#example-app',
})

Answer №1

If you're looking to implement a feature like this, you could consider the following approach:

Vue.component('parent', {
    template: ` <div style="padding: 10px; background-color: red; border: 1px solid black;">
                    <button @click="$emit('testevent')">Parent Button</button>
                    <button @click="test">Triggger Test Manueally</button>

                    <slot ></slot>
                </div>`,
    methods: {
        test () {
            alert('Test ok')
        },
    mounted: function() {
      this.$on('testevent', () => {
        this.test()
      })
    }
})

Vue.component('child', {
    template: ` <div style="padding: 10px; margin: 5px; background-color: green; border: 1px solid black;">
                    <button @click="$emit('testevent')">Child Button</button><br>
                    <slot></slot>
                </div>`,
    mounted: function() {
      this.$on('testevent', () => {
        this.$parent.$emit('testevent')
      })
    }
})

Vue.component('grandchild', {
    template: `<div style="padding:10px; margin: 5px; background-color: white; border: 1px solid black;">
                <button @click="$parent.$emit('testevent')">Grandchild Button</button>
                </div>`
})

new Vue({
    el: '#example-app',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="example-app" >
   <parent>
      <child>
         <grandchild></grandchild>
      </child>
   </parent>
</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

Searching and replacing text in VS Code and rearranging Vue.js lines

I keep encountering this tag in numerous files - all with the same path but various image files: <img id="logo" style="margin-left:170px;margin-top:8px;width:85px" class="shrunk" ...

Shuffle contents of a Div randomly

I'm currently in the process of developing a new website and I need to randomly move the news feed. To achieve this, I have created an array containing the list of news items. The array is then shuffled and placed within the news feed section. Althou ...

Tips for identifying the amount of <ul> elements contained within every div

Dealing with a large file structured in the same way, I am looking for a method to isolate a specific div, determine the number of ul's within it, and then iterate through each one to extract the value of every li element. <div class="experiment ...

Error: The 'length' property of the twitter object is not defined and cannot be read

I am trying to fetch data from my Twitter account using PHP and JSON. My PHP code is working fine, but I am facing an error with jQuery. Uncaught TypeError: Cannot read property 'length' of undefined $(document).ready(function() { var dm ...

Guide on sending images as props in a Vue.js component (using Vite instead of require due to compatibility issues)

This is the main component <template> <rooms-card roomImage="../../assets/images/room3.jpg" roomType="Duplex Room" roomDescription="Sami double bed 1 guest room 3 windows" roomPrice="$50/night" /> < ...

Assign a CSS class individually to each item within a v-for loop

I've been experimenting with Vue.js and I'm attempting to dynamically change the class of specific items in a v-for loop based on a checkbox selection. <template> <div> <ul> <div :class="{completed: d ...

Do we need to handle promise resolution after sending a response to the client?

After sending the response to the client, I have a requirement to execute an asynchronous function. res.json({}); someAsyncFunction(); //this function does not require await Is it considered problematic to call this function without awaiting its promise? ...

What methods can I use to evaluate the efficiency of my website?

Is there a way to assess and improve website performance in terms of load time, render time, and overall efficiency? I've heard of YSLOW for firebug, but am curious if there are any other tools or websites available for this purpose. ...

Where is the source of this ever-changing image?

Recently, I decided to dive into the world of jQuery and experiment with a plugin carousel. However, I must admit it is all a bit overwhelming for me at the moment. Currently, I have the plugin installed and I am struggling to get rid of the bottom scroll ...

The appearance of Recaptcha buttons is unattractive and seemingly impossible to

Let me start by saying that I have already looked into the issue of "Recaptcha is broken" where adjusting the line-height was suggested as a solution. Unfortunately, that did not work for me. After implementing Google's impressive Recaptcha on my web ...

Unlocking the power of dynamic text using a single form

My comment reply system is experiencing an issue where the first reply works fine, but subsequent replies are unable to get the reply text value. How can I ensure that all replies work properly based on the Razor code provided below? <h4>Comments< ...

What is the process of transferring JavaScript code to an HTML file using webpack?

I am looking to display an HTML file with embedded CSS, fonts, and JS (not linked but the content is inside). I have the CSS and fonts sorted out, but I am struggling to find a solution for the JavaScript. My project is based on Node.js. ...

Using AngularJS to Apply a Class with ng-repeat

Using ng-repeat in my markup, I am trying to add text to each li element and also include an additional class (besides the 'fa' class). This is what I have done so far: <ul class='social-icons' ng-repeat="social in myCtrl.socialArr" ...

Text area capacity

Is there a limit to the maximum capacity of a textarea for accepting text? The HTML page functions correctly when the text is limited to around 130-140 words. However, if the text exceeds this limit, it causes the page to hang without any response. The tex ...

The elastic image slideshow maintains the original size of the images and does not resize them

When utilizing the elastic image slider, I encounter a similar issue as described at Elastic Image Slideshow Not Resizing Properly. In the downloaded example, resizing the window works correctly. However, when trying to integrate the plugin with Twitter B ...

Checking for the presence of a specific function in a file using unit testing

I am curious if there is a possible way to utilize mocha and chai in order to test for the presence of a specific piece of code, such as a function like this: myfunction(arg1) { ...... } If the code has been implemented, then the test should return t ...

AngularJS - Creating a dynamic wizard experience using UI-Router

I have set up my routes using ui-router in the following way: $stateProvider .state('root', { url: "", templateUrl: 'path/login.html', controller: 'LoginController' }) .state('basket&a ...

Encountering issues with generating image files using createObjectURL after transitioning to NextJS 13 from version 10

I'm currently working on a website with the following functionality: Client side: making an API call to retrieve an image from a URL Server side: fetching the image data by URL and returning it as an arrayBuffer Client side: extracting the arrayBuffe ...

Setting up and customizing Express with Angular

Currently working on a straightforward Angular/Express todo-list app, I encountered some difficulties. As the project is still in progress, after running the code on localhost:3000, I noticed that {{ thing }} was displayed literally on the webpage. The di ...

Is the shift key being pressed during the onClick event in React?

To trigger an onClick event only when the meta(mac) / ctrl(win) key is pressed, follow these steps: This is what I attempted: const [shiftOn, setShiftOn] = useState(false) useEffect(() => { document.addEventListener('keydown', (e) => ...