问题描述
我有一个组件vue-datetimepicker
I have a component vue-datetimepicker
具有以下内容:
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')
}
}
以及来自父组件form-preview.vue
我正在尝试捕获它.
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.
推荐答案
this.$on
将侦听同一组件发出的事件.要侦听子组件发出的事件,您应该在父组件的模板部分的子组件上分配一个事件侦听器.因此,在form-preview.vue
的模板部分中,您应该有类似..
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" ... / >
然后在父组件的脚本部分中,您可以定义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)
}
}
请注意,事件处理程序将自动接收随事件发出的所有数据.如果要使其明确,可以使用@change="handleChange($event)"
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)"
这篇关于在父组件的子组件发出事件时捕获值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!