vue.js自定义select2指令并使用ajax远程获取值(包括鼠标滑动下拉分页)

2022-08-08,,,,

在用vue做下拉框时想到了select2,但是直接使用的话不能成功,不能获取下拉框的值,然后就想到了封装select指令,废话不多说 直接上代码
//封装v-select指令
封装的directives.js代码

Vue.directive('select2', {
     	 inserted: function (el, binding, vnode) {
         let options = binding.value || {};
         //默认值开始
         var option;
         for (var d = 0; d < options.value.length; d++) {
        	    var item = options.value[d]; 
        	     option = new Option(item.id, item.text, true, true); 
        	     $(el).select2().append(option);
        }
        //默认值结束
        $(el).select2(
                {
        		 width:"100%",
                 placeholder          : "===请输入关键字===",
                 allowClear: false,
                 minimumInputLength   : 0,
                 ajax: {
                	 xhrFields: {
 	                    withCredentials: true
 	                },
                     url:options.url,
                     type : 'post',
                     dataType: 'json',
                     delay: 500, //延迟0.5s加载防止过度查询
                     data: function (params) {//参数
                         return {
                             keyword: params.term,//关键字
                             pagesize:10, 
                             currpage: params.page || 1,
                         };
                     },
                     processResults: function (data, params) {
                    	 var id=options.id;
                    	 var text=options.name;
                         var arr = [];
                         //根据自己返回的json值做出相应的修改
     					for(var i in data.result.list){
     						arr.push({id:data.result.list[i][id],text:data.result.list[i][text]});
     					}
                         return {
                             results: arr,
     						pagination: { //鼠标下拉是否显示更多的值
     							more: data.result.totalPage>(params.page||1)
     						  }
                         };
                     },
                     cache: false
                 },
                 escapeMarkup: function (markup) { return markup; }
                }
        ).on("select2:select", (e) => {
              el.dispatchEvent(new Event('change', { target: e.target })); 
              options && options.onSelect && options.onSelect(e);
        })//在网上查找很多代码都没有下边这几行,以至于多选的时候删除一个选中的时候selectValue值不变(这想了好几天)
        .on("select2:unselect", (e) => {
            el.dispatchEvent(new Event('change', { target: e.target })); 
            options && options.onSelect && options.onSelect(e);
         });
     
      },

      update: function(el, binding, vnode,oldVnode) {
    	  console.log(el);
    	  console.log(binding);
    	  console.log(vnode);
    	  console.log(oldVnode);
     	  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");
      }
    });

html代码

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
<meta http-equiv="X-UA-Compatible" content="IE=emulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<!--以下css,js相信大家都有,可以改成自己的路径-->
<script type="text/javascript" src="jquery.min.js" ></script>
<script type="text/javascript" src="vue.js"></script>
<link rel="stylesheet" href="select2.min.css" />
<script type="text/javascript" src="select2.min.js" ></script>
<link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/font-awesome/4.6.0/css/font-awesome.min.css"/>
<script type="text/javascript" src="directives.js"></script> <!--刚才封装的js-->
<title>select2</title>
<style type="text/css">
        .example{
            text-align: center;
            padding:50px;
        }
        .content *{
            text-align: left;
        }
        .select{
            width: 160px;
        }
        </style>
</head>
<body>
<div class="example" id="vue-example">
        <select class="select" v-select2='optionst' v-model="selectValue" multiple title="asd" ></select>
        <br/>
        <span>结果:{{ value }}</span>
    </div>
<script type="text/javascript">
    var vueApp = new Vue({
      el: "#vue-example",
      data: { 
        value:["example2","example3"],  <!--单选值的时候直接写值"example2"-->
        optionst: {
        	selectValue:[{"id":"example2","text":"example2"},{"id":"example3","text":"example3"}],<!--可以设置默认值需为数组-->
            url: http://192.168.1.101/select2/selectExample   <!--修改成自己的接口地址-->
            id: "NO", <!--选择框的id对应返回数据的字段-->
            name: "NAME" <!--选择框的text对应返回数据的字段-->
        }
      }
    });
</script>
</body>
</html> 

应一些人的要求在代码中加入了默认值的代码

本文地址:https://blog.csdn.net/L19910311/article/details/107230817

《vue.js自定义select2指令并使用ajax远程获取值(包括鼠标滑动下拉分页).doc》

下载本文的Word格式文档,以方便收藏与打印。