2

I added a event listener to my document like this:

deleteTask(event){
     // myFunc
}

created() {
     document.addEventListener("keypress", this.deleteTask);
},

This happened in my Home.vue component. Now i want to remove this event listener in my Card.vue component. Like so:

document.removeEventListener("keypress", this.deleteTask);

This obviously doesn't work since this.deleteTask is not known in the Card.vue component. But i need the deleteTask func to stay in my Home.vue cause it operates on some arrays there. So my question is now: What is the best way to do this?

2 Answers 2

1

You could create an EventBus.

Create a new js file with:

import Vue from 'vue';
export const EventBus = new Vue();

Now you can in your Home.vue listen to events:

created() {
   ...
   EventBus.$on('removeListener', () => { document.removeEventListener("keypress", this.deleteTask); })
}

The event removeListener will then be called in Card.vue using EventBus.$emit('removeListener')

Sign up to request clarification or add additional context in comments.

2 Comments

Do i have to manage some imports to make this work? because im getting a error that EventBus is not defined in my Home.vue
Yes, you will have to import { EventBus } from 'path/to/js' in both components
0

Don't make it global, let it to listen only in your component:

<template>
  <div @keypress="deleteTask">
    ...
  </div>
</template>

1 Comment

But how do i then remove the task from my array which is in my Home.vue component? The problem is that i have a Home.vue component which holds a list component and this than holds a cardlist component and than a card component

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.