Capture events of underlying element in component
Asked Answered
P

1

2

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?

Painful answered 3/1, 2017 at 5:42 Comment(0)
D
3

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>
Disputable answered 3/1, 2017 at 6:14 Comment(1)
Thank you, although had to change to :on-change="onChange()"Painful

© 2022 - 2024 — McMap. All rights reserved.