Using Select2 (multiple selections) with vue.js

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

I'm new to vue and have followed their 'custom directive' at http://vuejs.org/examples/select2.html.

This works well when only selecting one item, but when you're selecting multiple items it only passes the first one. I need it to pass all values selected.

I have a jsfiddle set up displaying the code which is available here. https://jsfiddle.net/f3kd6f14/1/

The directive is as below;

 Vue.directive('select', {     twoWay: true,     priority: 1000,      params: ['options'],      bind: function() {         var self = this         $(this.el)                 .select2({                     data: this.params.options                 })                 .on('change', function() {                     self.set(this.value)                 })     },     update: function(value) {         $(this.el).val(value).trigger('change')     },     unbind: function() {         $(this.el).off().select2('destroy')     } 

Any help would be appreciated.

回答1:

this.value doesn't work like you expect when Select2 is in multiple value mode (more info here: Get Selected value from Multi-Value Select Boxes by jquery-select2?).

Try this (working fiddle here: https://jsfiddle.net/02rafh8p/):

Vue.directive('select', {     twoWay: true,     priority: 1000,      params: ['options'],      bind: function() {         var self = this         $(this.el)                 .select2({                     data: this.params.options                 })                 .on('change', function() {                     self.set($(self.el).val()) // Don't use this.value                 })     },     update: function(value) {         $(this.el).val(value).trigger('change')     },     unbind: function() {         $(this.el).off().select2('destroy')     } })  var vm = new Vue({     el: '#el',     data: {         selected: [], // Result is an array of values.          roles : [             { id: 1, text: 'hello' },             { id: 2, text: 'what' }         ]     } }) 


回答2:

In Vue 2, to get all select2 values onchange:

Change this:

.on('change', function () {   self.$emit('input', this.value); // Don't use this.value }); 

To this:

.on('change', function () {   self.$emit('input', $(this).val()); }); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!