将Select2选择绑定到Vue js模型数据

我正在使用select2来增强html选择元素。 我想将select元素的值绑定到Vue变量,但Select2似乎阻止了这一点。

在保留Select2行为的同时,实现此数据绑定和事件监听的最佳方法是什么。 我想这是将select2事件链接到Vue实例的情况。

我已经做了一个演示问题的小提琴 (不在下面运行,但在jsfiddle上工作):

$('#things').select2(); new Vue({ el: "#vue-example", data: { thing: null, thing2: null }, methods: { log: function(str) { $('#log').append(str + "
"); } } });
 select { width: 50%; } 
     
One Two Three Four Five

One Two Three Four Five
{{ $data | json }}

斯威夫特的回答是正确的。 您只需要识别并更新该代码以反映Select2中的差异。

http://jsfiddle.net/qfy6s9Lj/10/

 Vue.directive('selecttwo', { twoWay: true, bind: function () { $(this.el).select2() .on("select2:select", function(e) { this.set($(this.el).val()); }.bind(this)); }, update: function(nv, ov) { $(this.el).trigger("change"); } }); new Vue({ el: "#vue-example", data: { thing: null, thing2: null }, methods: { log: function(str) { $('#log').append(str + "
"); } } });
 select { width: 50%; } 
     


{{ $data | json }}

此解决方案适用于Chosen插件,但您可以使用Select2执行相同操作以使其工作:

http://jsfiddle.net/simplesmiler/qfy6s9Lj/8/

 Vue.directive('chosen', { twoWay: true, // note the two-way binding bind: function () { $(this.el) .chosen({ inherit_select_classes: true, width: '30%', disable_search_threshold: 999 }) .change(function(ev) { // two-way set this.set(this.el.value); }.bind(this)); }, update: function(nv, ov) { // note that we have to notify chosen about update $(this.el).trigger("chosen:updated"); } }); var vm = new Vue({ data: { city: 'Toronto', cities: [{text: 'Toronto', value: 'Toronto'}, {text: 'Orleans', value: 'Orleans'}] } }).$mount("#search-results"); 

更短的解决方案:

 Vue.directive('select2', { inserted(el) { $(el).on('select2:select', () => { const event = new Event('change', { bubbles: true, cancelable: true }); el.dispatchEvent(event); }); }, }); 

Trae的答案很好但是值已经存储在select元素上了,所以你需要做的就是调度事件让Vue知道我们已经改变了它。

只需简单地做:

  

我几天前为select2制作了一个插件。

https://github.com/halupi/vue-select2

希望能帮助到你!