捕获组件中底层元素的事件 [英] Capture events of underlying element in component
问题描述
尝试使用此组件。
<select2 v-model="value" :options="options" @change="onChange()"></select2>
@change
回调未被调用。我知道我可以使用 watch:{value:function(){...}
但是,有没有办法捕获底层标记事件?
The @change
callback is not getting called. I know that I can use watch: { value: function () { ... }
but, is there a way to capture underlying tag events?
推荐答案
在当前版本中, select2
组件无法处理 - 改变功能。为此,您必须修改 select2
组件,您必须再添加一个prop: onChange
并在组件内部执行在这个道具中传递的函数,更改将如下所示:
In the current version, select2
component does not handle on-change function. For this, you have to modify the select2
component, you have to add one more prop: onChange
and inside component execute the function passed in this prop, changes will be something like following:
Vue.component('select2', {
props: ['options', 'value', 'onChange'], //Added one more prop
template: '#select2-template',
mounted: function () {
var vm = this
$(this.$el)
.val(this.value)
// init select2
.select2({ data: this.options })
// emit event on change.
.on('change', function () {
vm.$emit('input', this.value)
//New addition to handle onChange function
if (this.onChange !== undefined) {
this.onChange(this.value)
}
})
},
watch: {
value: function (value) {
// update value
$(this.$el).select2('val', value)
},
options: function (options) {
// update options
$(this.$el).select2({ data: options })
}
},
destroyed: function () {
$(this.$el).off().select2('destroy')
}
})
现在,您可以传递一个将在onChange上执行的函数,如下所示:
Now, you can pass a function which will be executed onChange like following:
<select2 v-model="value" :options="options" :on-change="onChange()"></select2>
这篇关于捕获组件中底层元素的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!