Using Select2 (multiple selections) with vue.js

久未见 提交于 2019-12-06 07:21:34
David K. Hess

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' }
        ]
    }
})

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