catch value on event emit from child component in parent component

…衆ロ難τιáo~ 提交于 2019-12-13 01:54:05

问题


I have a component vue-datetimepicker

that has the following :

export default {
  name: 'vue-datetimepicker',
  data () {
    return {
      value: ''
    }
  },
  watch: {
    options: function (options) {
      // update options
      $(this.$el).datetimepicker({ data: options })
    }
  },
  mounted: function () {
    var vm = this
    var mycomp = $(this.$el).datetimepicker({})
    mycomp.on('dp.change', function (e) {
      vm.value = e.date
      vm.$emit('change', vm.value)
    })
  },
  destroyed: function () {
    $(this.$el).off().datetimepicker('destroy')
  }
}

and from the parent component form-preview.vue

I am trying to capture it.

    created() {
        this.$on('change', function(id){
            console.log('Event from parent component emitted', id)
        });
    },
    mounted: function() {

    },

I am expecting when I change datetime It should emit the change event. But nothing is getting printed in the console.


回答1:


this.$on will listen for events emitted by the same component. To listen for events emitted by a child component you should assign an event listener on the child component in the template section of the parent component. So in the template section of form-preview.vue you should have something like this ..

<vue-datetimepicker @change="handleChange" ... / >

Then in the script section in the parent component you can define your handleChange event handler ..

methods: {
    handleChange(value) {
        console.log('Event from child component emitted', value)
    }
}

Note that the event handler will automatically receive any data emitted with the event. If you want to make it explicit you can use @change="handleChange($event)"



来源:https://stackoverflow.com/questions/53902123/catch-value-on-event-emit-from-child-component-in-parent-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!