Select2加载远程数据

本文介绍了如何使用Select2插件在HTML中实现异步加载远程数据的功能,以满足大数据量下拉框的需求。通过示例代码展示了如何配置Select2的ajax选项,连接到后台接口,进行POST请求,以及处理返回的数据并实现分页。当输入达到一定字符长度时,触发加载更多数据。
现在项目中的数据越来越多,对于需求来说,普通的下拉框是不能满足现在的需求,于是想到了之前看到的select2这个插件可以异步加载,就像百度的搜索一样
下面就说一下具体该如何使用
<!DOCTYPE html>
<html>
<head>
    <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
    <script src="//cdn.bootcss.com/select2/4.0.3/js/select2.min.js"></script>
    <link href="//cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <link href="//cdn.bootcss.com/select2/4.0.3/css/select2.min.css" rel="stylesheet">

</head>
<body>

<select id="select2" </
在vue2 select中进行远程搜索数据回显,需要使用v-model来实现数据的双向绑定。 首先,在vue组件的data中定义一个数组来存储选中的数据: ``` data() { return { selectedData: [] } } ``` 然后,在vue2 select中使用v-model绑定该数组: ``` <template> <v-select v-model="selectedData" :items="items" :search-input.sync="search" label="name" item-value="id" item-text="name" :loading="loading" @search="searchData"></v-select> </template> ``` 在上面的代码中,items表示从远程获取的数据,search表示搜索关键字,loading表示数据是否正在加载。@search是vue2 select的一个事件,可以在搜索框输入内容时触发,我们可以在这里进行远程搜索。 最后,在searchData方法中,我们可以通过远程接口获取数据,并将已选中的数据回显到vue2 select中: ``` methods: { async searchData() { this.loading = true; // 调用远程接口获取数据 const res = await axios.get(`/api/search?keyword=${this.search}`); this.items = res.data; this.loading = false; // 将已选中的数据回显到vue2 select中 this.selectedData.forEach((item) => { const index = this.items.findIndex((i) => i.id === item.id); if (index !== -1) { this.$set(this.items[index], 'selected', true); } }); } } ``` 在上面的代码中,我们首先调用远程接口获取数据,并将数据存储到items数组中。然后,遍历已选中的数据,通过findIndex方法找到对应的数据在items数组中的索引,然后使用$set方法将selected属性设置为true,从而实现回显。 完整的代码示例: ``` <template> <v-select v-model="selectedData" :items="items" :search-input.sync="search" label="name" item-value="id" item-text="name" :loading="loading" @search="searchData"></v-select> </template> <script> import axios from 'axios'; export default { data() { return { items: [], search: '', loading: false, selectedData: [] } }, methods: { async searchData() { this.loading = true; // 调用远程接口获取数据 const res = await axios.get(`/api/search?keyword=${this.search}`); this.items = res.data; this.loading = false; // 将已选中的数据回显到vue2 select中 this.selectedData.forEach((item) => { const index = this.items.findIndex((i) => i.id === item.id); if (index !== -1) { this.$set(this.items[index], 'selected', true); } }); } } } </script> ```
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值