vue中使用select2

<template>
  <div >
        <div style="line-height: 50px;">
            <select class="select " v-select2='options' multiple="multiple"   v-model="selectValue"></select>
        </div>
        <div>
        </div>
  </div>
</template>

<script>
import * as $ from 'jquery'
import "../../../../static/css/select2.css";
import "../../../../js/select2.js"
export default {
    name:"Chanion",
    data(){
        return {
            selectValue: [],
            options: {
                data: [
                    { id: 0, text: 'name' },
                    { id: 1, text: 'name2' },
                    { id: 2, text: 'name3' },
                    { id: 3, text: 'name4' },
                    { id: 4, text: 'name5' }
                ]
            }
        }
    },
    directives: {
        select2: {
            inserted: function (el, binding, vnode) {
                debugger;
                let options = binding.value || {};
                $(el).select2(options).on("select2:select", (e) => {
                    el.dispatchEvent(new Event('change', {target: e.target}));
        
                });
            },
            update: function (el, binding, vnode) {
                debugger;
                for (var i = 0; i < vnode.data.directives.length; i++) {
                    if (vnode.data.directives[i].name == "model") {
                        $(el).val(vnode.data.directives[i].value);
                    }
                }
                $(el).trigger("change");
            },
        }
    },
    mounted() {
        
    },
    methods:{

    }
}
</script>

<style scoped>
.opinionTitle{
    font-size: 16px;
    height: 46px;
    line-height:46px;
    font-weight: 700;
    border-bottom: 1px solid gainsboro;
    color: green;
}
.textarea{
    width: 100%;
    height: 300px;
    border: 1px solid #DCDFE6;
}
.XBChange{
    color: #606266;
    border-radius: 4px;
    padding: 0 15px;
    height:28px;
    width: 554px;
    border: 1px solid #DCDFE6;
}
.select{
    color: #606266;
    border-radius: 4px;
    padding: 0 15px;
    line-height:28px !important;
    width: 700px;
    border: 1px solid #DCDFE6;
}

</style>

必须引入jquery、select2.js和select2.css这三个文件,否则会报错,其中selectValue必须是一个数组,但是在使用select2多选的时候由于自带了取消和点击取消方法,所以在selectValue中无法看到取消的结果,这时候selectValue其中的值是不对的,可以通过

        getChangeOpinion(){
            let a=[];
            $(".select2-selection__choice").toArray().forEach(item => {
                a.push(item.title);
            });
            console.log(a,"Aaa");
        }

来获取当前select框中已经选择的值。

posted @ 2021-07-06 10:47  奔跑的哈密瓜  阅读(2083)  评论(0编辑  收藏  举报