Passing events from nested components within a Vue.js slot

Recently, I started delving into Vue and encountered some challenges with passing events across different components. Currently, I'm working on a basic todo list application which allows users to add new tasks and delete existing ones. You can check out the repository for this project at https://github.com/Polenj86/vue-taskmanager.

The app's tree structure is as follows:

-root //App.vue
-- childcomponent // NewTask.vue
-- childcomponent // TasksWrapper.vue
   -- grandchildcomponent //Task.vue

My goal is to incorporate a button within Task.vue that enables me to delete a task from the root's tasks array. So far, I have only been able to achieve task deletion by clicking on the entire element using this method:

<app-component @click.native="deleteTask"></app-component>

methods: {
  deleteTask(index) {
    this.tasks.splice(index, 1)
  }
}

I am aiming to assign this delete functionality to the button inside the component rather than the entire component itself.

This is the code snippet for the grandchildren component:

<template lang="pug">
.panel.panel-default
    .panel-body
        slot(name="task-content")
    .panel-footer
        button.btn.btn-sm.btn-primary(@click="deleteTask") Delete task

</template>    

How should I communicate to the root that I want to initiate a delete action? I attempted to utilize an event emitter but I am unsure about what should be passed as the second argument in the emitter.

export default {    
    methods: {
        deleteTask() {
            this.$emit('taskWasDeleted', ???);
        }
    }
}

Any assistance would be greatly appreciated.

Answer №1

If Task.vue is not a direct child of App.vue, you can establish communication using a global EventBus.

In your main.js file, create an empty Vue instance to serve as the central event bus:

export const EventBus = new Vue();

Pass the index from v-for to the Task.vue component as a prop.

// In grandChild component or Task.vue
<app-component :taskIndex="index" :key="index"></app-component>

In Task.vue, emit an event with the index as the second parameter that was received as a prop.

<template lang="pug">
.panel.panel-default
    .panel-body
        slot(name="task-content")
    .panel-footer
        button.btn.btn-sm.btn-primary(@click="deleteTask") Delete task

</template> 

import {EventBus} from './main.js'
export default {    
    proos: ['tabIndex'],
    methods: {
        deleteTask() {
            EventBus.$emit('deleteTask', this.tabIndex);
        }
    }
} 

In the created hook of App.vue, listen for the deleteTask event.

//App.vue
<script>
import {EventBus} from './main.js'
export default{
    created(){
        EventBus.$on('deleteTask', (taskIndex) => {
            this.tasks.splice(taskIndex, 1)
        });
    }
}
</script> 

`View the fiddle

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

Struggling to make v-model functional with Composition API and Vuex

After scouring through numerous posts on stackoverflow and various websites, I am still unable to pinpoint the issue in my specific case. My app follows the composition api approach and utilizes a variable named modelStartDate (initialized on Jan 3, 2022) ...

Tips for retrieving the checked status of a Material UI <Checkbox/> component and changing it to false upon clicking a different icon (such as a delete icon)

Greetings! I have encountered a problem that I am hoping someone can assist me with. I am looking for information or guidance on how to handle a specific issue. The challenge I am facing involves accessing the checked property of a material-ui <Checkbo ...

Is there a way to iterate through two arrays simultaneously in React components?

Recently delving into the world of React, I am utilizing json placeholder along with axios to fetch data. Within my state, I have organized two arrays: one for posts and another for images. state = { posts : [], images : [] ...

Is there a way to automatically apply a class named "bottom" to the element with the ID "sidebar" when it reaches the bottom of its container?

I have implemented code that adds a CSS class called fixed to the element with ID #sidebar once it reaches a specific distance from the top of the webpage, depending on the page type (e.g. home, single, or page). In a similar manner, I am looking to add a ...

jQuery Issue DetectedSlight complication spotted with jQuery

I've encountered a peculiar problem with jQuery's contains function: HTML <span class="tag diaTags label label-info">Teststring<span data-role="remove"></span></span> JS When I directly use $('span.diaTags:contai ...

Utilize JSON data fetched from a URL to dynamically populate an HTML content

There is a JSON file located at a URL that looks like this: [{"tier":"SILVER","leagueName":"Tryndamere's Wizards","queueType":"RANKED_SOLO_5x5","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":18,"wins":411,"losses":430,"rank" ...

If the div is devoid of content, then remove the class

<div class="slider">content goes here</div> <div id="slider-2" class="active inactive">also some content here</div> <script type="text/javascript"> function checkEmpty( element ){ return !$.trim(element.html()) ...

Executing JavaScript function on AJAX update in Yii CGridView/CListView

Currently, I am integrating isotope with Yii for my CListView and CGridView pages to enhance their display. While everything functions smoothly, an issue arises when pagination is utilized, and the content on the page is updated via ajax, causing isotope ...

Text below a stationary header

I need some help with my code using material-ui-next beta.30. The issue I am facing is that the content within mui.Paper is appearing behind the AppBar instead of below it. Here's my current setup: import * as React from 'react'; import * a ...

Tips for displaying specific information using Javascript depending on the input value of an HTML form

I am working on an HTML form that includes a dropdown list with four different names to choose from. window.onload = function(){ document.getElementById("submit").onclick = displaySelectedStudent; } function displaySelectedStu ...

IE8 and IE9 encountering "Access is denied" error due to XML causing XDomainRequest (CORS) issue

Sorry if this seems repetitive, but I am unable to find a definitive answer to similar questions. Whenever I attempt to make a CORS request for XML, I consistently encounter an "Access is denied" JavaScript error in IE8. The code I am using is based on t ...

Updating a value using jQuery AJAX techniques

Using jQuery AJAX, I am loading the content of a page in this way: $(document).ready(function(){ $('#next').click(function(event){ $.ajax({ url: "load.php?start="+$('#lastid').text(), success: function(html){ $("#results"). ...

"Streamlining data entry with an uncomplicated HTML form input that accepts multiple values from a

As I understand it, a barcode scanner functions as nothing more than a keyboard that transmits keycode 13 after each scan. My task is straightforward: I have a basic form with only one input field and I want the ability to scan numerous barcodes and then c ...

Is it possible to set auto height for Jquery Fancybox when using within an Iframe?

Currently, I am utilizing Fancybox iframe form which has a fixed height of 350px. However, upon submitting the form, the resulting window only displays two lines of content. Is there a way to make the window adjust its height automatically based on the fo ...

Unable to implement the checkCollision function within the Snake game using JavaScript

My latest project involves creating a Snake game using canvas in JavaScript. I've managed to set up most of the game, but I'm having trouble with the collision check. Whenever the snake hits itself or the wall, the game crashes because I can&apos ...

Exploring the functionality of test code within an rxjs subscription by utilizing the powerful technique of jasmine

My goal is to test the code within an observable subscription: function bar(someStream$: Observable<number>) { someStream$.pipe( map((x) => x + 3), ).subscribe((result) => { SomeService.someMethod(result) }) } I want to ensure t ...

How can you extract elements from a JSON array into separate variables based on a specific property value within each element?

In the following JSON array, each item has a category property that determines its grouping. I need to split this array into separate JSON arrays based on the category property of each item. The goal is to extract all items with the category set to person ...

Combining Vue.js3 with a .NET 6 API and integrating Google login functionality

My website utilizes a vue.js Single Page Application, interacting with a .NET 6 API through ajax calls. I am looking to implement Google account login for users and authenticate them to the API by passing their Google ID or email. What would be the most ef ...

Angular 7's URL updates, but no other actions take place

I am new to posting here and feeling quite desperate. Currently, I am working with Angular 7 and facing an issue. The problem arises when I manually enter the desired URL, everything works perfectly. However, when I use RouterLink by clicking a button, the ...

What is the best way to continuously verify login and password credentials?

I am a newcomer to this industry and am facing a challenge with testing the process of entering the correct username and password using Selenium Webdriver. The current method of creating this process without a loop is extremely lengthy and monotonous. Here ...