Home > Back-end >  $emit not being caught by listener
$emit not being caught by listener

Time:08-24

I'm having an issue here that I can't seem to fix: I would like to have a simple toggle for a component using $emit

this is my index.vue :

    <div
      v-for="(filteredArticles, categoryKey) in groupedCategories"
      :key="categoryKey"
      
      @listen-button-event="toggle"
    >
      <CategoryWrapper :title="categoryKey" />
    </div>
  methods: {
    toggle () {
      alert('I did something')
      console.log('ping')
      this.isActive = !this.isActive
    }
  }

this is my component :

    <div
      :
      @click="changeComponent()"
    >
      <a>{{ title }}</a>
    </div>
  data () {
    return {
      isActive: false
    }
  },
  methods: {
    changeComponent () {
      this.$emit('listenButtonEvent')
    }
  }

Doesn't seem to do anything...

CodePudding user response:

listen-button-event shouldn't be on the div it should be on the CategoryWrapper Component.

<div
  v-for="(filteredArticles, categoryKey) in groupedCategories"
  :key="categoryKey"
  
  
>
  <CategoryWrapper :title="categoryKey" @listen-button-event="toggle" />
</div>

CodePudding user response:

Listeners need to be camelCas'ed like this

<CategoryWrapper :title="categoryKey" @listenButtonEvent="toggle" />

and not kebab-case'ed.

As you can see in the Vue devtools, since you're emitting listenButtonEvent here.

enter image description here


A better convention being emitting a update:listenButtonEvent btw, cannot find an official recommendation for that one again.

  • Related