小程序模糊匹配加上拉加载分页实现代码
时间: 2023-11-21 15:05:04 浏览: 35
以下是一个模糊匹配加上拉加载分页的小程序实现代码:
```
// pages/index/index.js
const MAX_LIMIT = 10 // 每页最多显示的条目数
Page({
data: {
keyword: '', // 搜索关键字
list: [], // 搜索结果列表
pageNum: 0, // 当前页码
hasMore: true // 是否还有更多数据
},
// 输入关键字时触发
onKeywordInput(e) {
this.setData({
keyword: e.detail.value.trim()
})
},
// 搜索按钮点击时触发
onSearch() {
this.setData({
pageNum: 0, // 搜索时重置当前页码
hasMore: true // 搜索时重置是否还有更多数据
})
this.search()
},
// 滚动到底部时触发
onScrollToLower() {
if (this.data.hasMore) {
this.search()
}
},
// 模糊匹配搜索
search() {
const db = wx.cloud.database()
// 构造查询条件
const reg = db.RegExp({
regexp: this.data.keyword,
options: 'i'
})
const where = {
name: reg
}
// 查询数据总数,用于判断是否还有更多数据
db.collection('items')
.where(where)
.count()
.then(res => {
const total = res.total
const hasMore = this.data.pageNum * MAX_LIMIT < total
this.setData({
hasMore
})
})
// 查询数据列表,分页加载
db.collection('items')
.where(where)
.orderBy('name', 'asc')
.skip(this.data.pageNum * MAX_LIMIT)
.limit(MAX_LIMIT)
.get()
.then(res => {
const list = this.data.pageNum === 0 ? res.data : this.data.list.concat(res.data)
this.setData({
list,
pageNum: this.data.pageNum + 1
})
})
}
})
```
在页面中,需要添加一个输入框和一个搜索按钮,以及一个列表组件用于显示搜索结果。同时,在页面的 `onLoad` 方法中还需要初始化云开发环境。
```
// pages/index/index.js
Page({
onLoad() {
wx.cloud.init({
env: 'your-env-id',
traceUser: true
})
}
})
```
其中,`your-env-id` 需要替换成你自己的云开发环境 ID。