Capture events of underlying element in component

心已入冬 提交于 2019-11-28 10:19:31

问题


Trying to use this component.

<select2 v-model="value" :options="options" @change="onChange()"></select2>

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?


回答1:


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')
  }
})

Now, you can pass a function which will be executed onChange like following:

<select2 v-model="value" :options="options" :on-change="onChange()"></select2>


来源:https://stackoverflow.com/questions/41437120/capture-events-of-underlying-element-in-component

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