Home > Net >  Vue JS emit event to child component from parent component not triggering
Vue JS emit event to child component from parent component not triggering

Time:03-08

I'm working in a Nuxt JS project. I have several components, and one of my components called ComplianceOptoutRawText includes a child component called ComplianceOptoutViaExternalService, and it's this child component where I'm using a v-on to listen for an $emit event from the ComplianceOptoutRawText so I can toggle a variable, but I'm not seeing it at all in my console logs and need to know what I'm doing wrong and need to change.

Here's my markup with everything that's appropriate:

ComplianceOptoutRawText

<template>
  <div>
    <div>
      <div >
        <ComplianceOptoutViaExternalService>
          <template #trigger>
            <button @click="$emit('shown-optout-intent', true)" type="button">here</button>
          </template>
        </ComplianceOptoutViaExternalService>
      </div>
    </div>
  </div>
</template>

And then the child component itself:

ComplianceOptoutViaExternalService

<template>
  <div>
    <slot name="trigger"></slot>
    <article v-show="wantsToOptOut" v-on:shown-optout-intent="hasShownOptoutIntent" >
      <validation-observer v-if="!didOptOut" ref="optoutServiceForm" key="optoutServiceForm" v-slot="{ handleSubmit }" tag="section">
        <form>
          ...
        </form>
      </validation-observer>
    </article>
  </div>
</template>

<script>
export default {
  data () {
    return {
      wantsToOptOut: false,
      isOptingOut: false,
      didOptOut: false
    }
  },
  methods: {

    /*
    ** User has shown opt out intent
    */
    hasShownOptoutIntent (value) {
      this.wantsToOptOut = !this.wantsToOptOut
    }

  }
}
</script>

Note that my child component uses a slot, this is so I can position everything as needed in the parent component, but at it's core, I have a parent component emitting a value and then listening for it via v-on:shown-optout-intent="hasShownOptoutIntent" which runs the hasShownOptoutIntent method.

But I never see anything from the button, even if I console.log this. What am I missing?

CodePudding user response:

I'm doing something similar with an embedded component, so it's perhaps worth trying:

<button @click="$emit('update:shown-optout-intent', true)" type="button">here</button>

... and then:

v-on:shown-optout-intent.sync="hasShownOptoutIntent"

As an aside, it's safe to remove v-on and use: :shown-optout-intent.

  • Related