VueJS how to listen to an event from a method not from a template

I am sending an event from a child component to a parent. I want to intercept a signal using a method in the parent. But the listen function always works regardless of whether the event was selected. Please note that I use separate file components and Vue-router.

Aside, I found very few VueJS examples using separate file components, and for noob, dragging and dropping from a simple Vue application into one file onto several separate 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'm doing wrong?

+4
source share
1 answer

on , .

- :

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

methods:

eventIsEmitted: function(status) {
    if (status == 'accepted') {
        this.stage = 2;
    }
}
+4

Source: https://habr.com/ru/post/1673496/


All Articles