Ryan H
Ryan H

Reputation: 2953

Vue JS emit event to child component from parent component not triggering

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 class="tw-hidden md:tw-block tw-font-bold tw-mb-4">
        <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" class="tw-bg-white tw-p-4 md:tw-p-6 tw-rounded-xl tw-text-gray-800 tw-border tw-border-gray-300 tw-text-left tw-mt-4">
      <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?

Upvotes: 0

Views: 1187

Answers (1)

Wayne Smallman
Wayne Smallman

Reputation: 1720

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.

Upvotes: 1

Related Questions