uni-app第三天

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)
        }
    }
    
    // 为便于项目中其他地方使用这个管道符功能,我们将其在main.js中进行全局封装
    Vue.filter('formatNum', (price) => {
        return if(price) Number(value).toFixed(2)
    })

3、上拉加载

    // uni-app界面触底事件
    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()
    // await执行完毕后 关闭下拉刷新
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 400)
  }

5、加入购物车逻辑

    // 模块的 mutations 方法
    mutations: {
      addToCart(state, item) {
        // 根据 商品id 查询购物车中是否存在这件商品
        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) {
    // 1. 清除还未执行的定时器
    clearTimeout(this.timer);

    // 2. 创建一个新的定时器
    this.timer = setTimeout(() => {
      this.keyword = e.value;   
      console.log(this.keyword);
    }, 500);
  }
}