1、分页

商品列表的分页实现是后台根据前端请求的页面大小、页码位置,去数据库中查询指定位置的数据然后返回给前端。比如页面大小为8,要查第3页的数据,则跳过2*8条数据,然后返回接下来的8条数据。

实现滚动加载:页面刚一加载完成并不需要请求所有数据,只显示一部分。当用户下拉到页面底部时,再去请求数据并拼接到商品数据列表中。通过vue-infinite-scroll插件实现滚动加载,在框架末尾插入加载div,并且可以在其中放入加载动画

<div v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
  <img v-if="showLoading" src="../../static/loading-svg/loading-spinning-bubbles.svg">//加载的矢量动画
</div>

通过busy可以控制是否启用加载,在loadMore函数中定义你的加载操作,然后通过setTimeout按时间间隔响应加载请求

new Vue({
  el: '#app',
  data: {
    data: [],
    busy: false        //一开始不用加载
  },
  methods: {
    loadMore(){        //滚动加载操作
      this.busy = true;
      setTimeout(() => {
        this.page++;
        this.getGoodsList(true);
      }, 1000);
    }
  }
});

2、排序

商品按价格排序在服务器端实现,通过mongoose中的sort函数对数据库查询结果按price关键字排序,之后返回给前端。在前端发送排序请求:

    sortPrice(){        //按价格排序
      this.sortFlag=this.sortFlag==1?-1:1;
      this.page=1;
      this.getGoodsList();
    }

其中1为升序,-1降序,排序之后需要将页码置1,然后再去请求商品列表

3、按价格筛选

服务器端根据前端请求的最大值(priceGt)、最小值(priceLt)去数据库中查询指定价位之间的商品并返回给前端,利用mongoose的查询函数find中的params参数中设置$gt,$lt查询指定区间的商品   

let params={
    salePrice:{$gt:req.query.priceGt,$lt:req.query.priceLt}
  };

商品前端请求:

getGoodsList(split){
      let param={                    //设置get请求的参数
        pageSize:this.pageSize,
        page:this.page,
        sortFlag:this.sortFlag,
        priceGt:this.priceGt,
        priceLt:this.priceLt
 };
      this.showLoading=true;         //启用加载svg动画
      axios.get("/goods",{
          params:param
      }).then(response =>{
        let res=response.data;
        if(res.status==0){
          if(split){                 //split==true,需要滚动追加页数
            this.goodsList=this.goodsList.concat(res.result.list);
            if(res.result.count==0){    //返回0条数据,禁用滚动
              this.busy=true;
            }else{
              this.busy = false;
            }
          }else{
            this.goodsList=res.result.list;
          }
        }else{
          console.log("从服务器请求数据失败!");
        }
      });

    服务器端处理: 

router.get('/',(req,res,next)=>{
  //获取get请求中的参数
  let pageSize=parseInt(req.query.pageSize);
  let page=parseInt(req.query.page);
  let sortFlag=req.query.sortFlag;
  let skipPiece=(page-1)*pageSize;                //分页查询,跳过前面skip条数据
  let params={
    salePrice:{$gt:req.query.priceGt,$lt:req.query.priceLt}
  };

  //利用goods模板调用mongooseAPI进行数据库查询、排序、跳到指定页
  let goodsModel=goods.find(params).sort({'salePrice':sortFlag}).skip(skipPiece).limit(pageSize);
  goodsModel.exec((err,goodsDoc)=>{
    "use strict";
    if (err){
      res.json({
        status:1,
        msg:err.message
      })
    }else {
      res.json({                                //利用res将查询结果返回
        status:0,
        msg:'',
        result:{
          count:goodsDoc.length,
          list:goodsDoc
        }
      })
    }
  })
});
Logo

前往低代码交流专区

更多推荐