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框中已經選擇的值。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM