【问题标题】:Capture events of underlying element in component捕获组件中底层元素的事件
【发布时间】:2017-05-17 04:02:00
【问题描述】:

尝试使用this 组件。

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

@change 回调未被调用。我知道我可以使用watch: { value: function () { ... },但是,有没有办法捕获底层标签事件?

【问题讨论】:

    标签: javascript select2 vue.js


    【解决方案1】:

    在当前版本中,select2 组件不处理 on-change 功能。为此,您必须修改 select2 组件,您必须再添加一个 prop:onChange 并在组件内部执行此 prop 中传递的函数,更改将如下所示:

    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 上执行的函数,如下所示:

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

    【讨论】:

    • 谢谢,虽然不得不改成:on-change="onChange()"
    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2011-11-22
    • 2014-11-27
    • 1970-01-01
    • 2018-02-23
    相关资源
    最近更新 更多