Vuejs指令绑定模型

时间:2016-12-20 14:43:46

标签: javascript vue.js select2

我正在使用Vuejs 1.0指令将select字段(单个和多个)转换为Select2 jQuery插件字段。

Vue.directive('select2', {
    twoWay: true,
    priority: 1000,

    params: ['max-items'],

    bind: function () {
        var self = this;
        console.log(self.params);

        $(this.el)
            .select2({
                maximumSelectionLength: self.params.maxItems,
                theme: 'bootstrap',
                closeOnSelect: true
            })
            .on('change', function () {
                var i, len, option, ref, values;
                if (self.el.hasAttribute('multiple')) {
                    values = [];
                    ref = self.el.selectedOptions;
                    for (i = 0, len = ref.length; i < len; i++) {
                        option = ref[i];
                        values.push(option.value);
                    }
                    return self.set(values);
                } else {
                    return self.set(self.el.value);
                }
            })
    },
    update: function (value, oldValue) {
        $(this.el).val(value).trigger('change')
    },
    unbind: function () {
        $(this.el).off().select2('destroy')
    }
});

一切正常。我也试图将模型绑定到字段的值,但似乎无法使其正确绑定。

<select class="form-control" name="genre" v-model="upload.genre" v-select2="">
<option value="50">Abstract</option>
<option value="159">Acapella</option>
<option value="80">Acid</option>
...
</select>

upload.genre属性不会自动更新。

1 个答案:

答案 0 :(得分:3)

v-model实际上是传递prop和更改事件设置值的语法糖,所以跟随:

<input v-model="something">

相当于

<input v-bind:value="something" v-on:input="something = $event.target.value">

您还必须进行类似的更改,您可以在vue团队提供的select2示例中看到此类型代码。

  .on('change', function () {
    vm.$emit('input', this.value)
  })

使用Vue 1.0

当你使用vue 1.0时,指令的two-way选项有助于将数据写回Vue实例,你需要传入twoWay:true。此选项允许在指令内使用this.set(value):

Vue.directive('select2', {
  twoWay: true,
  bind: function () {
    this.handler = function () {
      // set data back to the vm.
      // If the directive is bound as v-select2="upload.genre",
      // this will attempt to set `vm.upload.genre` with the
      // given value.
      this.set(this.el.value)
    }.bind(this)
    this.el.addEventListener('input', this.handler)
  },
  unbind: function () {
    this.el.removeEventListener('input', this.handler)
  }
})

并在HTML中:

<select class="form-control" name="genre" v-select2="upload.genre">
相关问题