Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS how to listen to event from method not from template

I am sending an event from a child component to it's parent. I want to intercept the signal via a method in the parent. But the listening function fires always regardless of whether an event has been emitted. Note that I am using single file components and Vue-router.

As an aside, I have found very few VueJS examples use single file components, and for a noob, transpiling from the simple Vue app in one file to multiple single file components can be confusing.

Parent:

<template>
 ....html here
</template>
<script>
  import Child from './Child.vue'

  export default {
  name: 'Parent',
  data () {
    return {
     stage: 1
    }
  },
  components: {
    Child
  },
  created: function () {
    // the following line always runs even when listen for non-existent event eg this.$on('nonsense'...)
    this.$on('child-event', this.stage = 2)
  }
  }

child:

<template>
  <button v-on:click="sendEvent" type="button" class="btn btn-success">Next</button>
</template>

<script>
  export default {
  name: 'Child',
  data () {
    return {
      response_status: 'accepted'
    }
  },
  methods: {
    sendEvent: function () {
      this.$emit('child-event', 'accepted')
    }
  }

Any idea what I am doing wrong?

like image 327
Don Smythe Avatar asked Mar 09 '23 11:03

Don Smythe


1 Answers

Another way of setting the on event would be referencing the listener method directly from the place where you call the child component.

On your parent template you could do something like:

<Child v-on:child-event="eventIsEmitted"></Child>

On your methods:

eventIsEmitted: function(status) {
    if (status == 'accepted') {
        this.stage = 2;
    }
}
like image 50
SUB0DH Avatar answered Mar 12 '23 02:03

SUB0DH