Capture events of underlying element in component

后端 未结 1 1602
青春惊慌失措
青春惊慌失措 2020-12-21 11:39

Trying to use this component.


The @chan

相关标签:
1条回答
  • 2020-12-21 12:00

    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>
    
    0 讨论(0)
提交回复
热议问题