问题
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());
});
来源:https://stackoverflow.com/questions/35154138/using-select2-multiple-selections-with-vue-js