随手记录一下 Vue 下来框搜索 select2 封装成vue

引入布局文件

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>


/** * select2封装 */ Vue.directive('select2', { inserted: function (el, binding, vnode) { let options = binding.value || {}; $(el).select2(options).on("select2:select", (e) => { // v-model looks for // - an event named "change" // - a value with property path "$event.target.value" el.dispatchEvent(new Event('change', {target: e.target})); //说好的双向绑定,竟然不安套路 }); }, update: function (el, binding, vnode) { 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"); } }); /*使用案例*/ /* <select v-select2="" v-model="sale.carNum" required="required" class="form-control select"> <option value=""></option> <option v-for="item in options.carId" :value="item.value">{{item.text}}</option> </select> */

  

原文地址:https://www.cnblogs.com/louby/p/9153489.html