1、如何限制搜索历史的个数以及数据持久化
可以使用数组的pop方法删除数组最后一个元素并将新的元素添加到数组的最前面
this.historyList.unshift(this.keyword)
this.historyList = [...new Set(this.historyList)]
if(this.historyList.length > 4){
this.historyList.pop()
}
uni.setStorageSync('keywords', this.historyList)
this.historyList = uni.getStorageSync('keywords') || []
2、给价格后面保留小数点后两位
使用:toFixed() 给数字类型提供的方法,返回的是字符串 配合
<view class="goods-price">¥{{ product.goods_price |formatNum }}</view>管道符进行返回
filters: {
formatNum(val){
return val.toFixed(2)
}
}
Vue.filter('formatNum', (price) => {
return if(price) Number(value).toFixed(2)
})
3、上拉加载
onLoad({ query, cid }){
this.params.query = query || ''
this.params.cid = cid || ''
},
onReachBottom(){
if(this.productList.length === this.total) return this.$shotMsg('数据加载完毕~')
if(this.isLoading) return
this.params.pagenum ++
this.getProductList()
},
created(){
this.getProductList()
},
methods: {
async getProductList(){
this.isLoading = true
const { meta: {status}, message } = await this.$http.get('/goods/search', this.params)
if(status !== 200) return this.$msg()
this.productList = [...this.productList, ...message.goods]
this.total = message.total
this.isLoading = false
}
}
4、下拉刷新
- 需要在 `pages.json` 里,找到的当前页面的pages节点,并在 `style` 选项中开启 `enablePullDownRefresh`。
- 当处理完数据刷新后,`uni.stopPullDownRefresh` 可以停止当前页面的下拉刷新。
async onPullDownRefresh(){
this.params.pagenum = 1
this.productList = []
await this.getProductList()
setTimeout(() => {
uni.stopPullDownRefresh()
}, 400)
}
5、加入购物车逻辑
mutations: {
addToCart(state, item) {
const existedItem = state.cartItems.find(x => x.goods_id === item.goods_id)
if (existedItem) {
existedItem.goods_count++
} else {
state.cartItems.push(item)
}
}
}
6、输入框防抖处理
methods: {
inputHandler(e) {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.keyword = e.value;
console.log(this.keyword);
}, 500);
}
}