版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/damys/article/details/88100270
components 搜索组件
index.js
import { KeywordModel } from '../../models/keyword.js'
import { BookModel } from '../../models/book.js'
import { paginationBev } from '../behaviors/paginationBev.js'
const keywordModel = new KeywordModel()
const bookModel = new BookModel()
Component({
// 引用行为
behaviors: [paginationBev],
/**
* 组件的属性列表
*/
properties: {
more:{
type:String,
// 属性改变时执行, 可以使用随机数
// newVal 是变化的那个子字段的值, oldVal 为空, changedPath 包含子字段的字段名相关信息
observer: 'loadMore'
}
},
/**
* 组件的初始数据
*/
data: {
historyWords:[],
hotWords:[],
q:'',
searching:false,
loading:false,
showLoadingIcon:false
},
// 在组件实例进入页面节点树时执行, 进行页面初始化数据
attached(){
// const historyWords = keywordModel.getHistory()
// const hotWords = keywordModel.getHot()
this.setData({
historyWords: keywordModel.getHistory()
})
keywordModel.getHot().then(res=>{
this.setData({
hotWords: res.hot
})
})
},
/**
* 组件的方法列表
*/
methods: {
loadMore: function (newVal, oldVal, changedPath) {
// 同时 发送两个, 一次只能发送一条,锁的
if (!this.data.q) return
// if (this.data.loading) return // 加载锁的
if (this._isLocked()) return // 加载锁的
if (!this.hasMore()) return // 是否加载
this._locked()
// this.data.loading = true
bookModel.search(this.getCurrentStart(), this.data.q).then(res => {
// 拼装数据
this.setMoreData(res.books)
this._unLocked()
// this.data.loading = false
// 细节:断网,请求失败,有网络后,表求仍失败的问题, 需要使用第二个回调
// 失败处理:解锁
}, () => {
this._unLocked()
})
// ---------- 优化,使用上面的行为 --------------
// const length = this.data.dataArray.length
// this.data.loading = true
// bookModel.search(length, this.data.q).then(res=>{
// const tempArray = this.data.dataArray.concat(res.books)
// console.log(tempArray)
// this.setData({
// dataArray: tempArray,
// loading:false
// })
// })
},
// Cancel
onCancel(event){
// 重置数据
this.initialize()
this.triggerEvent('cancel',{},{})
},
onDelete(){
// 重置数据
this.initialize()
this.setData({
searching: false,
q:''
})
},
// Confirm Search
onConfirm(event){
// const word = event.detail.value
// keywordModel.addToHistory(word)
// word, q 是一样的, 搜索成功后加入缓存
// 显示加载图标
this._showLoadingIcon();
// 切换用户搜索的状态,显示相关面板
this.setData({
searching:true
})
// 重置数据
this.initialize()
// 获取输入框,点击tag
const q = event.detail.value || event.detail.text
bookModel.search(0, q).then(res=>{
// 使用行为, 第一次加载数据
this.setMoreData(res.books)
this.setTotal(res.total)
this.setData({
// dataArray:res.books,
q:q // 点击tag 后动态设置输入框值
})
keywordModel.addToHistory(q)
// 加载数据后,显示加载图标
this._hideLoadingIcon();
})
},
// ------------ 重构 ----------------
// 显示加载图标
_showLoadingIcon(){
this.setData({
showLoadingIcon:true
})
},
// 隐藏加载图标
_hideLoadingIcon() {
this.setData({
showLoadingIcon: false
})
},
// 是否加锁
_isLocked(){
return this.data.loading ? true : false
},
// 加锁
_locked(){
this.setData({
loading:true
})
},
// 解锁
_unLocked(){
this.setData({
loading:false
})
}
// 滑动加载
// 1. scroll-view
// 2. page 页面中使用 onReachBottom
}
})