代码之家  ›  专栏  ›  技术社区  ›  Simon R

与vue.js一起使用Select2(多选)

  •  2
  • Simon R  · 技术社区  · 10 年前

    我是初来乍到的,在 http://vuejs.org/examples/select2.html .

    这在只选择一个项目时很好,但在选择多个项目时,它只传递第一个项目。我需要它传递所有选定的值。

    我设置了一个jsfiddle来显示这里可用的代码。 https://jsfiddle.net/f3kd6f14/1/

    指令如下:;

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

    任何帮助都将不胜感激。

    2 回复  |  直到 10 年前
        1
  •  7
  •   Community Mohan Dere    9 年前

    this.value 当Select2处于多值模式时,无法按预期工作(更多信息请点击此处: Get Selected value from Multi-Value Select Boxes by jquery-select2? ).

    试试这个(这里的工作小提琴: 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
  •  -1
  •   aleixfabra    9 年前

    在Vue 2中,要在更改后获取所有select2值:

    更改此设置:

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

    为此:

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