Vue中使用select2无法获取数据问题
在vue项目中使用jquery的select2插件,无法获取到下拉框的值,后来看文档通过封装组件的形式解决了这一问题* select2封装*/Vue.directive('select2', {inserted: function (el, binding, vnode) {let options = binding.value || {};...
·
在vue项目中使用jquery的select2插件,无法获取到下拉框的值,后来看文档通过封装组件的形式解决了这一问题
* 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");
}
});
在使用时就直接可以用v-select2
就可以了
/*使用案例*/
<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>
用到的文件
注意:
在模式框中使select2时因为层级问题无法捕捉搜索框,在style设置z-index也不行,最后删除了modal中的tabindex="-1"
就可以了,也是经验所得,希望大家使用的时候注意。
<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>
2019/8/27更新
注:动态创建的select2下拉框的高度会发生改变,主要是.select2-selection–single属性高度被强制改变。自己修改高度即可。如下图
<style type="text/css">
.select2-container .select2-selection--single{
height:calc(2.95rem + 2px);
}
</style>
select2 ajax动态加载数据,动态查询数据
$('.user').select2({
ajax: {
url: ip+'/data/listuser',
dataType: 'jsonp',
jsonp: "callback",
data: function (params) {
var query = {
orgids: '',
s: params.term//搜索框中的值
}
//alert(JSON.stringify(query))
// Query parameters will be ?search=[term]&type=public
return query
},
processResults: function (data) {
//将获取到的数据整理成select2格式
var options = new Array();
for(var i=0;i<data.length;i++){
var userinfo=JSON.parse(data[i].userinfo);
options.push({ //获取select2个必要的字段,id与text
id : userinfo.xingming+"|"+userinfo.gonghao, //取出items中Code赋值给id
text : userinfo.xingming+"|"+userinfo.gonghao //取出items中CodeName赋值给text
});
};
return {
results: options //返回数据
};
},
cache: true
},
placeholder: "输入姓名搜索...",
language: "zh-CN",
allowClear: true, //允许手动删除选择的值
minimumInputLength:0, //最小输入的可搜索
escapeMarkup: function (markup) { return markup; }, // 字符转义处理自定义格式化防止xss注入
formatSelection: function formatRepoSelection(repo){return repo.text;}
});
更多推荐
已为社区贡献5条内容
所有评论(0)