Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

javascript - Capture events of underlying element in component

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...