【问题标题】:Using Select2 (multiple selections) with vue.js在 vue.js 中使用 Select2(多选)
【发布时间】:2023-03-14 21:22:01
【问题描述】:

我是 vue 的新手,并且在 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')
    }

任何帮助将不胜感激。

【问题讨论】:

    标签: vue.js select2


    【解决方案1】:

    当 Select2 处于多值模式时,this.value 无法正常工作(更多信息: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' }
            ]
        }
    })
    

    【讨论】:

    • 好答案.. 现在,如何指定默认选择的选项?
    • 只需将默认值分配给 selected 而不是空数组。
    【解决方案2】:

    在 Vue 2 中,获取所有 select2 值 onchange:

    改变这个:

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

    到这里:

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

    【讨论】:

    • 这会导致内部无限循环终止应用程序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 2019-05-25
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 2019-06-26
    相关资源
    最近更新 更多