关于vuejs2:vue.js select2多重选择

vue.js select2 multiple select

许多天以来,我一直在寻找该错误的答案。 我尝试了许多替代方法,但没有任何效果。

我需要选择多个值。 当我选择多个值时,我的代码会挂起,但是当我使用一个选择时,它可以与self.$emit('input', this.value)一起使用。 我需要选择多个值。

Select2.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<template>
    <select multiple class="input-sm" :name="name">
        <slot></slot>
    </select>
</template>
<style src="select2/dist/css/select2.min.css"></style>
<style src="select2-bootstrap-theme/dist/select2-bootstrap.min.css"></style>


    import Select2 from 'select2';

    export default{
        twoWay: true,
        priority: 1000,
        props: ['options', 'value', 'name'],
        data(){
            return{
                msg: 'hello'
            }
        },
        mounted(){
            var self = this;
            $(this.$el)
                .select2({theme:"bootstrap", data: this.options})
                .val(this.value)
                .trigger('change')
                .on('change', function () {
                    //self.$emit('input', this.value) //single select worked good
                    self.$emit('input',  $(this).val()) // multiple select
                })
        },
        watch: {
            value: function (value) {
                $(this.$el).val(value).trigger('change');
            },
            options: function (options) {
                $(this.$el).select2({ data: options })
            }
        },
        destroyed: function () {
            $(this.$el).off().select2('destroy')
        }
    }

新的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    <p>
Selected: {{ model.users_id }}
</p>
              <select2 :options="options" v-model="model.users_id" name="options[]" style="width: 1000px; height: 1em;" class="form-control">
           <option value="0">default</option>
            </select2>

    export default {
            data(){
                return {
                    model: {
                        'users_id': [],
                    },
                    options: [],

components:{
            'select2': Select2
         },


似乎您使用了select2的包装器的Vue文档示例作为基础。 我已经修改了包装器,以在此处处理多项选择。

我希望您遇到的主要问题是如果执行此操作:

1
self.$emit('input',  $(this).val()) // multiple select

您将陷入无限循环,因为您要发射一个新数组,它将触发手表,

1
2
3
value: function (value) {
    $(this.$el).val(value).trigger('change');
},

触发更改,触发手表等

要解决此问题,只需检查传递到手表中的值是否与select的值相同,如果是,则忽略它。 这是我的做法。

1
2
3
4
5
value: function (value) {
  // check to see if the arrays contain the same values
  if ([...value].sort().join(",") !== [...$(this.$el).val()].sort().join(","))
    $(this.$el).val(value).trigger('change');
},

还要注意,我将其变成了它自己的组件select2Multiple。 您可能想要一个组件来处理多个选定值,而另一个组件则要处理单个值。


正如我在这里回答的那样:
将Select2(多项选择)与vue.js结合使用

更改此:

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

对此:

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