怎么做网站美工,企业融资是做什么的,企业邮箱模板,怎么设置网站权限文章目录 说明细节一#xff1a;首页滑动到底部#xff0c;需要查询下一页的商品界面预览页面实现 细节二#xff1a;当页面滑动到下方#xff0c;出现一个回到顶端的悬浮按钮细节三#xff1a;商品分列说明优化前后效果对比使用回溯算法实现ControllerService回溯算法 优… 文章目录 说明细节一首页滑动到底部需要查询下一页的商品界面预览页面实现 细节二当页面滑动到下方出现一个回到顶端的悬浮按钮细节三商品分列说明优化前后效果对比使用回溯算法实现ControllerService回溯算法 优化减少图片的网络请求数据表增加字段将数据表中已有数据的宽高比计算出来并更新到数据表中修改商品发布页面的代码Service改进 优化考虑分页的分组高宽比总和平衡页面代码ControllerService回溯算法 页面整体代码 说明
之前已经在【UniApp开发小程序】小程序首页(展示商品、商品搜索、商品分类搜索)【后端基于若依管理系统开发】这篇文章中介绍了首页的实现但是当时的实现并不是完善的因为项目开发是一个持续的过程也因为我是个人的第一次尝试开发这种类型的项目很多细节没有提前构思清楚因此这篇文章作为一个补充用来优化前面的一些问题
细节一首页滑动到底部需要查询下一页的商品
界面预览
当滑动底部的时候底部出现”正在加载“字样同时向后端发送请求获取下一页的商品数据 当商品被全部加载出之后显示“没有更多了”字样 页面实现
下面的方法可以监听用户滑动页面到达底部当滑动到底部的时候调用方法查询更多商品
// 监听用户滑动到底部
onReachBottom() {this.getMoreProductVo();
},注意当还有商品没有被查询出来时才会调用listProductVo方法去找服务端查询数据。如果没有了则提示“没有更多了”
/*** 获取下一页的商品*/
getMoreProductVo() {if (this.productList[0].length this.productList[1].length this.total) {// this.$refs.uToast.show({// type: warning,// message: 已经加载完所有商品数据,// duration: 1000// })} else {if (this.loadData ! true) {// console.log(--------------------------获取下一页商品---------------------------)this.page.pageNum;// 显示正在加载this.loadmoreStatus loading;this.listProductVo().then(() {if (this.productList[0].length this.productList[1].length this.total) {// 没有更多了this.loadmoreStatus nomore;} else {// 加载更多this.loadmoreStatus loadmore;}});}}
},细节二当页面滑动到下方出现一个回到顶端的悬浮按钮
增加一个标签
!-- 回到上方按钮 --
u-back-top :scroll-topscrollTop/u-back-top因为标签绑定了一个变量需要声明出来
// 用来控制滚动到最上方
scrollTop: 0除此之外还需要实时记录滚动的位置
// 在滑动过程实时获取现在的滚动条位置并保存当前的滚动条位置
onPageScroll(e) {this.scrollTop e.scrollTop;
},细节三商品分列
说明
上篇文章中使用了最简单的方式来实现分列那就是直接遍历一遍商品数组依次将商品分到第一列和第二列但是这样会出现两列商品高度不平衡的情况如下图 因此我们需要更换一种分组策略用来平衡两列商品内容的高度这样视觉效果更好。问题可以理解为假设有十个物品每个物品的长度不太一样要求将这些物品分到两组中最后两组物品长度总和最接近请问需要怎么来分这两个组
优化前后效果对比 使用回溯算法实现
因为采用的是分页查询而且每次查询出来的数据量并不大因此可以直接使用回溯算法获取所有的分组情况最后选择出高度差距最小的分组方案即可
Controller
/*** 查询商品Vo列表*/
PreAuthorize(ss.hasPermi(market:product:list))
PostMapping(/listProductVo)
ApiOperation(获取商品列表)
public AjaxResult listProductVo(RequestBody ProductVo productVo) {startPage();if (productVo.getProductCategoryId() ! null) {// --if-- 当分类不为空的时候只按照分类来搜索productVo.setKeyword(null);}if (productVo.getIsSearchStar() ! null productVo.getIsSearchStar() true) {productVo.setStarPeopleId(getLoginUser().getUserId());}ListProductVo productVoList productService.selectProductVoList(productVo);// 将productVoList分成两组要求两组的高度之和相差最小ListProductVo[] groups productService.splitToTwoGroups(productVoList);MapString, Object map new HashMap();TableDataInfo pageMes getDataTable(productVoList);map.put(pageMes, pageMes);map.put(groups, groups);return AjaxResult.success(map);
}Service
Override
public ListProductVo[] splitToTwoGroups(ListProductVo productVoList) {ListProductVo[] resultArr new List[2];for (int i 0; i resultArr.length; i) {resultArr[i] new ArrayList();}/// 数据准备// 获取每个图片的高宽比MapLong, Double idAndRatioMap new HashMap();// 存储所有商品的idListLong idList new ArrayList();long start System.currentTimeMillis();for (ProductVo productVo : productVoList) {idList.add(productVo.getId());if (productVo.getPicList() ! null productVo.getPicList().size() 0) {try {BufferedImage sourceImg ImageIO.read(new URL(productVo.getPicList().get(0)).openStream());idAndRatioMap.put(productVo.getId(), sourceImg.getHeight() * 1.0 / sourceImg.getWidth());} catch (IOException e) {throw new RuntimeException(e);}} else {idAndRatioMap.put(productVo.getId(), 0.0);}}System.out.println(分组时间 (System.currentTimeMillis() - start) ms);/// 深度优先遍历找出所有方案选择两组高度差距最小的分组方案GroupDivide groupDivide new GroupDivide();groupDivide.dfsSearch(idList, 0, new ArrayList(), idAndRatioMap);/// 最后处理分组ListLong group1 groupDivide.bestGroup1;ListLong group2 new ArrayList();for (Long id : idList) {if (group1.indexOf(id) -1) {group2.add(id);}}for (ProductVo productVo : productVoList) {if (group1.indexOf(productVo.getId()) ! -1) {resultArr[0].add(productVo);} else {resultArr[1].add(productVo);}}return resultArr;
}由于下面的方法获取每个图片的高宽比都需要进行网络请求因此速度较慢因此需要进行优化
BufferedImage sourceImg ImageIO.read(new URL(productVo.getPicList().get(0)).openStream());
idAndRatioMap.put(productVo.getId(), sourceImg.getHeight() * 1.0 / sourceImg.getWidth());回溯算法
为了加速算法的求解其中使用了减枝策略不去搜索没有必要搜索的方案
package com.shm.algorithm;import com.ruoyi.common.utils.clone.CloneUtil;import java.util.ArrayList;
import java.util.List;
import java.util.Map;/*** 首页商品数据分组** Author dam* create 2023/8/30 14:12*/
public class GroupDivide {/*** 最小间距*/private double minOffSet Double.MAX_VALUE;/*** 存储最好的第一组*/public ListLong bestGroup1null;public void dfsSearch(ListLong idList, int begin, ListLong curGroup1, MapLong, Double idAndRatioMap) {if (begin idList.size()) {// 递归完成return;}for (int i begin; i idList.size(); i) {curGroup1.add(idList.get(i));// 计算组1的长度-组2的长度double offSet calculateGroup1DifHeifGroup2Hei(idList, curGroup1, idAndRatioMap);if (offSet minOffSet) {// 如果当前差距已经大于最小差距执行剪枝因为如果再往第一组增加图片的话那差距只会更大没必要再往下搜索了// 删除最后一个元素curGroup1.remove(curGroup1.size() - 1);continue;} else if (Math.abs(offSet) minOffSet) {// 找到更小的间距保存最优解minOffSet Math.abs(offSet);bestGroup1 CloneUtil.arrayListClone(curGroup1);}dfsSearch(idList, i 1, curGroup1, idAndRatioMap);// 删除最后一个元素curGroup1.remove(curGroup1.size() - 1);}}/*** 计算第一组的图片的总高度 减去 第二组图片的总高度** param idList* param group1* param idAndRatioMap* return*/private double calculateGroup1DifHeifGroup2Hei(ListLong idList, ListLong group1, MapLong, Double idAndRatioMap) {double sum1 0, sum2 0;for (Long id : idList) {if (group1.indexOf(id) -1) {sum2 idAndRatioMap.get(id);}else {sum1 idAndRatioMap.get(id);}}return sum1 - sum2;}}
优化减少图片的网络请求
因为图片的高宽比是一个不变量可以将其作为一个属性存储到数据表中这样只需要查询出来即可不再需要使用网络请求来获取但是需要在存储图片到数据表之前获取高宽比并将该属性进行存储
数据表增加字段 将数据表中已有数据的宽高比计算出来并更新到数据表中
因为我的数据表中已经存在了一些图片数据为了小程序地正确运行需要对这批数据进行修复即为每张图片补充高宽比。因为数据表的数据量不大而且是一次性任务直接每次修改单条数据即可。如果数据量很大可以使用多线程和分批批量修改来优化修复速度
Overridepublic void updatePictureSheetSetAspectRatio() {Picture picture new Picture();picture.setType(0);// 取消使用分页clearPage();ListPicture pictureList pictureMapper.selectPictureList(picture);for (Picture picture1 : pictureList) {String address picture1.getAddress();try {BufferedImage sourceImg ImageIO.read(new URL(address));picture1.setAspectRatio(sourceImg.getHeight() * 1.0 / sourceImg.getWidth());pictureMapper.updatePicture(picture1);} catch (IOException e) {throw new RuntimeException(e);}}}修改商品发布页面的代码
现在数据表需要保存图片的高宽比虽然可以直接由服务端在保存图片之前计算高宽比但是这样还是要发送很多网络请求影响接口的并发性能因此建议由客户端来计算高宽比然后直接上传给服务端服务端直接将数据保存即可
/**
* 上传闲置商品
*/
uploadSellProduct() {// console.log(上传闲置商品picList: JSON.stringify(this.picList));if (this.product.productCategoryId) {if (this.picList.length 0) {this.$refs.uToast.show({type: error,message: 商品图片没有上传成功})} else {this.setPicAspectRatio().then(() {// console.log(即将上传的商品 JSON.stringify(this.product));uploadSellProduct(this.product).then(res {this.$refs.uToast.show({type: success,message: 您的商品已经发布到平台})setTimeout(() {uni.reLaunch({url: /pages/index/index})}, 1000)}).catch(error {console.log(error: JSON.stringify(error));this.$refs.uToast.show({type: error,message: 商品发布失败})});});}} else {this.$refs.uToast.show({type: error,message: 请选择分类})}
},
/*** 设置图片的宽高比*/
setPicAspectRatio() {return new Promise((resolve, reject) {this.product.picList [];let promises [];for (let i 0; i this.picList.length; i) {let picUrl this.picList[i];promises.push(this.getAspectRatio(picUrl).then((res) {let pic {address: picUrl,aspectRatio: res}this.product.picList.push(pic);console.log(当前图片高宽比设置完成);}))}Promise.all(promises).then(() {console.log(所有图片高宽比设置完成this.product.picList: JSON.stringify(this.product.picList));resolve();})})
},
/*** 获取单个图片的高宽比* param {Object} url*/
getAspectRatio(url) {return new Promise((resolve, reject) {uni.getImageInfo({src: url,success: function(res) {let aspectRatio res.height / res.width;resolve(aspectRatio);}});})
},注意点
因为getAspectRatio方法获取图片的高宽比发送网络请求因此使用Promise来确保高宽比获取成功才resolve在上传商品之前需要先设置商品所对应的所有图片的高宽比。如果图片有多张需要等待所有图片的高宽比都设置完成本文使用Promise.all(promises)来等待所有图片的高宽比都设置完成再resolve
Service改进
因为已经将图片的高宽比存储到数据表中因此不需要再发送网路请求直接获取属性值即可
Override
public ListProductVo[] splitToTwoGroups(ListProductVo productVoList) {ListProductVo[] resultArr new List[2];for (int i 0; i resultArr.length; i) {resultArr[i] new ArrayList();}/// 数据准备// 获取每个图片的高宽比MapLong, Double idAndRatioMap new HashMap();// 存储所有商品的idListLong idList new ArrayList();long start System.currentTimeMillis();for (ProductVo productVo : productVoList) {idList.add(productVo.getId());if (productVo.getPicList() ! null productVo.getPicList().size() 0) {
// try {
// BufferedImage sourceImg ImageIO.read(new URL(productVo.getPicList().get(0)).openStream());
// idAndRatioMap.put(productVo.getId(), sourceImg.getHeight() * 1.0 / sourceImg.getWidth());
// } catch (IOException e) {
// throw new RuntimeException(e);
// }idAndRatioMap.put(productVo.getId(), productVo.getPicList().get(0).getAspectRatio());} else {idAndRatioMap.put(productVo.getId(), 0.0);}}System.out.println(分组时间 (System.currentTimeMillis() - start) ms);/// 深度优先遍历找出所有方案选择两组高度差距最小的分组方案GroupDivide groupDivide new GroupDivide();groupDivide.dfsSearch(idList, 0, new ArrayList(), idAndRatioMap);/// 最后处理分组ListLong group1 groupDivide.bestGroup1;ListLong group2 new ArrayList();for (Long id : idList) {if (group1.indexOf(id) -1) {group2.add(id);}}for (ProductVo productVo : productVoList) {if (group1.indexOf(productVo.getId()) ! -1) {resultArr[0].add(productVo);} else {resultArr[1].add(productVo);}}return resultArr;
}【测试】 在不需要发送网络请求之后可以看到获取图片高宽比的时间被大大减少 优化考虑分页的分组高宽比总和平衡
虽然上面已经使用算法来平衡两列的高宽比总和了但是还存在一个问题即商品数据是分页查询的比如第第一页查询的结果是第一列的高宽比总和大于第二列的高宽比总和。那么为了可以更好地平衡两列的高宽比总和第二页数据的查询结果应该是第二列的高宽比总和大于第一列的高宽比总和。为了处理这个问题在使用回溯算法的时候需要接收当前已渲染页面的两列宽高比这样才能方便更好地进行决策
页面代码
从下面的代码中可以很直观地看到每次分页查询都更新两列对应地高宽比总和并在发送请求的时候带上这两个参数
/**
* 查询商品vo集合
*/
listProductVo() {
return new Promise((resolve, reject) {// 设置当前两列的高宽比总和this.searchForm.sumAspectRatioOfColumn1 this.sumAspectRatioOfColumn1;this.searchForm.sumAspectRatioOfColumn2 this.sumAspectRatioOfColumn2;listProductVo(this.searchForm, this.page).then(res {// console.log(listProductVo: JSON.stringify(res))let productVoList res.data.pageMes.rows;this.total res.data.pageMes.total;// this.productList [// [],// []// ];// for (var i 0; i productVoList.length; i) {// if (i % 2 0) {// // 第一列数据// this.productList[0].push(productVoList[i]);// } else {// // 第二列数据// this.productList[1].push(productVoList[i]);// }// }let groups res.data.groups;for (var i 0; i groups[0].length; i) {if (groups[0][i].picList ! null groups[0][i].picList.length 0) {this.sumAspectRatioOfColumn1 groups[0][i].picList[0].aspectRatio;}}for (var i 0; i groups[1].length; i) {if (groups[1][i].picList ! null groups[1][i].picList.length 0) {this.sumAspectRatioOfColumn2 groups[1][i].picList[0].aspectRatio;}}this.productList[0] this.productList[0].concat(groups[0]);this.productList[1] this.productList[1].concat(groups[1]);resolve();})})},Controller
/*** 查询商品Vo列表*/
PreAuthorize(ss.hasPermi(market:product:list))
PostMapping(/listProductVo)
ApiOperation(获取商品列表)
public AjaxResult listProductVo(RequestBody ProductVo productVo) {startPage();if (productVo.getProductCategoryId() ! null) {// --if-- 当分类不为空的时候只按照分类来搜索productVo.setKeyword(null);}if (productVo.getIsSearchStar() ! null productVo.getIsSearchStar() true) {productVo.setStarPeopleId(getLoginUser().getUserId());}ListProductVo productVoList productService.selectProductVoList(productVo);// 将productVoList分成两组要求两组的高度之和相差最小ListProductVo[] groups productService.splitToTwoGroups(productVoList, productVo.getSumAspectRatioOfColumn1(), productVo.getSumAspectRatioOfColumn2());MapString, Object map new HashMap();TableDataInfo pageMes getDataTable(productVoList);map.put(pageMes, pageMes);map.put(groups, groups);return AjaxResult.success(map);
}Service
Override
public ListProductVo[] splitToTwoGroups(ListProductVo productVoList, Double sumAspectRatioOfColumn1, Double sumAspectRatioOfColumn2) {ListProductVo[] resultArr new List[2];for (int i 0; i resultArr.length; i) {resultArr[i] new ArrayList();}/// 数据准备// 获取每个图片的高宽比MapLong, Double idAndRatioMap new HashMap();// 存储所有商品的idListLong idList new ArrayList();long start System.currentTimeMillis();for (ProductVo productVo : productVoList) {idList.add(productVo.getId());if (productVo.getPicList() ! null productVo.getPicList().size() 0) {
// try {
// BufferedImage sourceImg ImageIO.read(new URL(productVo.getPicList().get(0)).openStream());
// idAndRatioMap.put(productVo.getId(), sourceImg.getHeight() * 1.0 / sourceImg.getWidth());
// } catch (IOException e) {
// throw new RuntimeException(e);
// }idAndRatioMap.put(productVo.getId(), productVo.getPicList().get(0).getAspectRatio());} else {idAndRatioMap.put(productVo.getId(), 0.0);}}System.out.println(分组时间 (System.currentTimeMillis() - start) ms);/// 深度优先遍历找出所有方案选择两组高度差距最小的分组方案GroupDivide groupDivide new GroupDivide();groupDivide.dfsSearch(idList, 0, new ArrayList(), idAndRatioMap,sumAspectRatioOfColumn1,sumAspectRatioOfColumn2);/// 最后处理分组ListLong group1 groupDivide.bestGroup1;ListLong group2 new ArrayList();for (Long id : idList) {if (group1.indexOf(id) -1) {group2.add(id);}}for (ProductVo productVo : productVoList) {if (group1.indexOf(productVo.getId()) ! -1) {resultArr[0].add(productVo);} else {resultArr[1].add(productVo);}}return resultArr;
}回溯算法
package com.shm.algorithm;import com.ruoyi.common.utils.clone.CloneUtil;import java.util.List;
import java.util.Map;/*** 首页商品数据分组** Author dam* create 2023/8/30 14:12*/
public class GroupDivide {/*** 最小间距*/private double minOffSet Double.MAX_VALUE;/*** 存储最好的第一组*/public ListLong bestGroup1 null;public void dfsSearch(ListLong idList, int begin, ListLong curGroup1, MapLong, Double idAndRatioMap, Double sumAspectRatioOfColumn1, Double sumAspectRatioOfColumn2) {if (begin idList.size()) {// 递归完成return;}for (int i begin; i idList.size(); i) {curGroup1.add(idList.get(i));// 计算组1的长度-组2的长度double offSet calculateGroup1DifHeifGroup2Hei(idList, curGroup1, idAndRatioMap, sumAspectRatioOfColumn1, sumAspectRatioOfColumn2);if (offSet minOffSet) {// 如果当前差距已经大于最小差距执行剪枝因为如果再往第一组增加图片的话那差距只会更大没必要再往下搜索了// 删除最后一个元素curGroup1.remove(curGroup1.size() - 1);continue;} else if (Math.abs(offSet) minOffSet) {// 找到更小的间距保存最优解minOffSet Math.abs(offSet);bestGroup1 CloneUtil.arrayListClone(curGroup1);}dfsSearch(idList, i 1, curGroup1, idAndRatioMap, sumAspectRatioOfColumn1, sumAspectRatioOfColumn2);// 删除最后一个元素curGroup1.remove(curGroup1.size() - 1);}}/*** 计算第一组的图片的总高度 减去 第二组图片的总高度** param idList* param group1* param idAndRatioMap* param sumAspectRatioOfColumn1* param sumAspectRatioOfColumn2* return*/private double calculateGroup1DifHeifGroup2Hei(ListLong idList, ListLong group1, MapLong, Double idAndRatioMap, Double sumAspectRatioOfColumn1, Double sumAspectRatioOfColumn2) {// 设置初始值double sum1 sumAspectRatioOfColumn1, sum2 sumAspectRatioOfColumn2;for (Long id : idList) {if (group1.indexOf(id) -1) {sum2 idAndRatioMap.get(id);} else {sum1 idAndRatioMap.get(id);}}return sum1 - sum2;}}
页面整体代码
【index页面】
templateview classcontentu-toast refuToast/u-toast!-- 回到上方按钮 --u-back-top :scroll-topscrollTop/u-back-topview styledisplay: flex;align-items: center;u-search placeholder请输入商品名称 v-modelsearchForm.keyword searchlistProductVo :showActionfalse:clearabledtrue/u-searchtext classiconfont stylefont-size: 35px; clickselectCategory()#xe622;/text/viewu-row customStylemargin-top: 10px gutter10 alignstart v-ifproductList[0].length0loadDatafalseu-col span6 classcol v-for(data,index) in productList :keyindexview classproductVoItem v-for(productVo,index1) in data :keyindex1clickseeProductDetail(productVo)u--image v-ifproductVo.picList!nullproductVo.picList.length0 :showLoadingtrue:srcproductVo.picList[0].address width100%:heightproductVo.picList[0].aspectRatio*100% radius10 modewidthFix :lazy-loadtrue:fadetrue duration450 errorreloadPir(productVo.picList[0].address)!-- 加载失败展示 --view sloterror stylefont-size: 24rpx;加载失败/view!-- 加载中提示 --template v-slot:loadingu-loading-icon colorred/u-loading-icon/template/u--image!-- u--image v-else :showLoadingtrue :srcsrc clickclick/u--image --view classproductMestext classproductName【{{productVo.name}}】/texttext{{productVo.descriptionnull?:productVo.description}}/text/viewview styledisplay: flex;align-items: center;!-- 现价 --view classprice¥text classnumber{{productVo.price}}/text/{{productVo.unit}}/viewview stylewidth: 10px;/view!-- 原价 --view classoriginPrice¥{{productVo.originalPrice}}/{{productVo.unit}}/view/viewview styledisplay: flex;align-items: center;u--image :srcproductVo.avatar width20 height20 shapecircle/u--imageview stylewidth: 10px;/viewview {{productVo.nickname}}/view/view/view/u-col/u-row!-- 显示加载相关字样 --u-loadmore v-ifproductList[0].length0loadDatafalse :statusloadmoreStatus /u-empty v-ifproductList[0].length0loadDatafalse modedata texColor#ffffff iconSize180iconColor#D7DEEB text所选择的分类没有对应的商品,请重新选择 textColor#D7DEEB textSize18 marginTop30/u-emptyview stylemargin-top: 20px; v-ifloadDatatrueu-skeleton :loadingtrue :animatetrue rows10/u-skeleton/view!-- 浮动按钮 --FloatButton clickcellMyProduct()u--image :srcfloatButtonPic shapecircle width60px height60px/u--image/FloatButton/view
/templatescriptimport FloatButton from /components/FloatButton/FloatButton.vue;import {listProductVo} from /api/market/product.js;import pictureApi from /utils/picture.js;import Vue from vue;import {debounce} from /utils/debounce.jsexport default {components: {FloatButton},onShow: function() {let categoryNameList uni.getStorageSync(categoryNameList);if (categoryNameList) {this.categoryNameList categoryNameList;this.searchForm.productCategoryId uni.getStorageSync(productCategoryId);this.searchForm.keyword this.getCategoryLayerName(this.categoryNameList);uni.removeStorageSync(categoryNameList);uni.removeStorageSync(productCategoryId);this.listProductVo();}},data() {return {title: Hello,// 浮动按钮的图片floatButtonPic: require(/static/cellLeaveUnused.png),searchForm: {// 商品搜索关键词keyword: ,productCategoryId: undefined},productList: [[],[]],loadData: false,// 用来锁定防止多次同时进行websocket连接lockReconnect: false,// 心跳一次间隔的时间单位毫秒heartbeatTime: 5000,page: {pageNum: 1,pageSize: 10},// 总数据条数total: 0,// 数据加载状态loadmoreStatus: loadmore,// 用来控制滚动到最上方scrollTop: 0,// 分别存储两列的高宽比总和sumAspectRatioOfColumn1: 0,sumAspectRatioOfColumn2: 0,}},onLoad() {},created() {this.loadData true;this.listProductVo().then(() {this.loadData false;});this.initWebsocket();// this.getMoreProductVo debounce(this.getMoreProductVo);},// 监听用户滑动到底部onReachBottom() {this.getMoreProductVo();},// 在滑动过程实时获取现在的滚动条位置并保存当前的滚动条位置onPageScroll(e) {this.scrollTop e.scrollTop;},methods: {/*** 查询商品vo集合*/listProductVo() {return new Promise((resolve, reject) {// 设置当前两列的高宽比总和this.searchForm.sumAspectRatioOfColumn1 this.sumAspectRatioOfColumn1;this.searchForm.sumAspectRatioOfColumn2 this.sumAspectRatioOfColumn2;listProductVo(this.searchForm, this.page).then(res {// console.log(listProductVo: JSON.stringify(res))let productVoList res.data.pageMes.rows;this.total res.data.pageMes.total;// this.productList [// [],// []// ];// for (var i 0; i productVoList.length; i) {// if (i % 2 0) {// // 第一列数据// this.productList[0].push(productVoList[i]);// } else {// // 第二列数据// this.productList[1].push(productVoList[i]);// }// }let groups res.data.groups;for (var i 0; i groups[0].length; i) {if (groups[0][i].picList ! null groups[0][i].picList.length 0) {this.sumAspectRatioOfColumn1 groups[0][i].picList[0].aspectRatio;}}for (var i 0; i groups[1].length; i) {if (groups[1][i].picList ! null groups[1][i].picList.length 0) {this.sumAspectRatioOfColumn2 groups[1][i].picList[0].aspectRatio;}}this.productList[0] this.productList[0].concat(groups[0]);this.productList[1] this.productList[1].concat(groups[1]);resolve();})})},/*** 获取下一页的商品*/getMoreProductVo() {if (this.productList[0].length this.productList[1].length this.total) {// this.$refs.uToast.show({// type: warning,// message: 已经加载完所有商品数据,// duration: 1000// })} else {if (this.loadData ! true) {// console.log(--------------------------获取下一页商品---------------------------)this.page.pageNum;// 显示正在加载this.loadmoreStatus loading;this.listProductVo().then(() {if (this.productList[0].length this.productList[1].length this.total) {// 没有更多了this.loadmoreStatus nomore;} else {// 加载更多this.loadmoreStatus loadmore;}});}}},/*** 跳转到卖闲置页面*/cellMyProduct() {console.log(我要卖闲置);uni.navigateTo({url: /pages/sellMyProduct/sellMyProduct})},/*** 获取高宽比 乘以 100%*/getAspectRatio(url) {return pictureApi.getAspectRatio(url);},/*** 选择分类*/selectCategory() {uni.navigateTo({url: /pages/sellMyProduct/selectCategory})},/*** 获取商品名称*/getCategoryLayerName() {let str ;for (let i 0; i this.categoryNameList.length - 1; i) {str this.categoryNameList[i] /;}return str this.categoryNameList[this.categoryNameList.length - 1];},/*** 查看商品的详情*/seeProductDetail(productVo) {// console.log(productVo:JSON.stringify(productVo))uni.navigateTo({url: /pages/product/detail?productVo encodeURIComponent(JSON.stringify(productVo))})},/*** 重新加载图片*/reloadPir(pic) {console.log(图片加载失败pic pic)},/*** 创建websocket连接*/initWebsocket() {console.log(this.socket: JSON.stringify(this.$socket))// this.$socket null刚刚进入首页还没有建立过websocket连接// this.$socket.readyState0 表示正在连接当中// this.$socket.readyState1 表示处于连接状态// this.$socket.readyState2 表示连接正在关闭// this.$socket.readyState3 表示连接已经关闭if (this.$socket null || (this.$socket.readyState ! 1 this.$socket.readyState ! 0)) {this.$socket uni.connectSocket({url: ws://10.23.17.146:8085/websocket/ uni.getStorageSync(curUser).userName,success(res) {console.log(WebSocket连接成功, res);},})// console.log(this.socket: this.$socket)// 监听WebSocket连接打开事件this.$socket.onOpen((res) {console.log(websocket连接成功)Vue.prototype.$socket this.$socket;// 连接成功开启心跳this.headbeat();});// 连接异常this.$socket.onError((res) {console.log(websocket连接出现异常);// 重连this.reconnect();})// 连接断开this.$socket.onClose((res) {console.log(websocket连接关闭);// 重连this.reconnect();})}},/*** 重新连接*/reconnect() {// console.log(重连);// 防止重复连接if (this.lockReconnect true) {return;}// 锁定防止重复连接this.lockReconnect true;// 间隔一秒再重连避免后台服务出错时客户端连接太频繁setTimeout(() {this.initWebsocket();}, 1000)// 连接完成设置为falsethis.lockReconnect false;},// 开启心跳headbeat() {// console.log(websocket心跳);var that this;setTimeout(function() {if (that.$socket.readyState 1) {// websocket已经连接成功that.$socket.send({data: JSON.stringify({status: ping})})// 调用启动下一轮的心跳that.headbeat();} else {// websocket还没有连接成功重连that.reconnect();}}, that.heartbeatTime);},}}
/scriptstyle langscss.content {padding: 20rpx;.col {width: 50%;}.productVoItem {margin-bottom: 20px;.productMes {overflow: hidden;text-overflow: ellipsis;display: -webkit-box;/* 显示2行 */-webkit-line-clamp: 2;-webkit-box-orient: vertical;.productName {font-weight: bold;}}.price {color: #F84442;font-weight: bold;.number {font-size: 22px;}}.originPrice {color: #A2A2A2;font-size: 15px;// 给文字添加中划线text-decoration: line-through;}}}
/style【上传销售商品页面】
templateview classcontaineru-toast refuToast/u-toastview classcontentview classitemview classlabelName商品名称/viewu--input placeholder请输入商品名称 bordersurround v-modelproduct.name/u--input/viewu-divider text商品描述和外观/u-divider!-- 商品描述 --u--textarea v-modelproduct.description placeholder请输入商品描述 height150/u--textarea!-- 图片上传 --viewimageUpload v-modelpicList maxCount9/imageUpload/viewu-divider text分类选择/自定义标签/u-divider!-- 分类选择/自定义标签 --view classitemview classlabelName分类/viewview classselectTextClass clickselectCategory{{getCategoryLayerName()}}/view/view!-- 商品的属性 新度 功能完整性 --view classitemview classlabelName成色/viewview classcolumnClassview :classproduct.finenessindex?selectTextClass:textClassv-for(finessName,index) in finenessList :keyindex clickchangeFineness(index){{finessName}}/view/view/viewview classitemview classlabelName功能状态/viewview classcolumnClassview :classproduct.functionalStatusindex?selectTextClass:textClassv-for(functionName,index) in functionList :keyindexclickchangeFunctionalStatus(index){{functionName}}/view/view/viewu-row customStylemargin-bottom: 10pxu-col span5view classitemview classlabelName数量/viewu--input placeholder请输入商品数量 bordersurround v-modelproduct.number/u--input/view/u-colu-col span7view classitemview classlabelName计量单位/viewu--input placeholder请输入计量单位 bordersurround v-modelproduct.unit/u--input/view/u-col/u-row!-- 价格 原价 现价 --u-divider text价格/u-divideru-row customStylemargin-bottom: 10pxu-col span6view classitemview classlabelName原价/viewu-input placeholder请输入原价 bordersurround v-modelproduct.originalPrice color#ff0000bluroriginalPriceChangeu--text text¥ slotprefix margin0 3px 0 0 typeerror/u--text/u-input/view/u-colu-col span6view classitemview classlabelName出售价格/viewu-input placeholder请输入出售价格 bordersurround v-modelproduct.price color#ff0000blurpriceChangeu--text text¥ slotprefix margin0 3px 0 0 typeerror/u--text/u-input/view/u-col/u-rowu-button text出售 sizelarge typeprimary clickuploadSellProduct/u-button/view/view
/templatescriptimport imageUpload from /components/ImageUpload/ImageUpload.vue;import {uploadSellProduct} from /api/market/product.jsexport default {components: {imageUpload},onShow: function() {let categoryNameList uni.getStorageSync(categoryNameList);if (categoryNameList) {this.categoryNameList categoryNameList;this.product.productCategoryId uni.getStorageSync(productCategoryId);uni.removeStorageSync(categoryNameList);uni.removeStorageSync(productCategoryId);}},data() {return {product: {name: ,descripption: ,picList: [],productCategoryId: undefined,number: 1,unit: 个,isContribute: 0,originalPrice: 0.00,price: 0.00,// 成色fineness: 0,// 功能状态functionalStatus: 0,brandId: 0},value: dasdas,categoryNameList: [选择分类],finenessList: [全新, 几乎全新, 轻微使用痕迹, 明显使用痕迹, 外观破损],functionList: [功能完好无维修, 维修过可正常使用, 有小问题不影响使用, 无法正常使用],picList: [],}},methods: {getCategoryLayerName() {let str ;for (let i 0; i this.categoryNameList.length - 1; i) {str this.categoryNameList[i] /;}return str this.categoryNameList[this.categoryNameList.length - 1];},/*** 价格校验* param {Object} price 价格*/priceVerify(price) {if (isNaN(price)) {this.$refs.uToast.show({type: error,message: 输入的价格不是数字请重新输入})return false;}if (price 0) {this.$refs.uToast.show({type: error,message: 输入的价格不能为负数请重新输入})return false;}if (price.toString().indexOf(.) ! -1 price.toString().split(.)[1].length 2) {this.$refs.uToast.show({type: error,message: 输入的价格小数点后最多只有两位数字请重新输入})return false;}return true;},originalPriceChange() {let haha this.priceVerify(this.product.originalPrice);if (haha false) {console.log(haha: haha);this.product.originalPrice 0.00;console.log(this.product JSON.stringify(this.product));}},priceChange() {if (this.priceVerify(this.product.price) false) {this.product.price 0.00;}},/*** 修改成色* param {Object} index*/changeFineness(index) {this.product.fineness index;},/*** 修改功能状态* param {Object} index*/changeFunctionalStatus(index) {this.product.functionalStatus index;},/*** 上传闲置商品*/uploadSellProduct() {// console.log(上传闲置商品picList: JSON.stringify(this.picList));if (this.product.productCategoryId) {if (this.picList.length 0) {this.$refs.uToast.show({type: error,message: 商品图片没有上传成功})} else {this.setPicAspectRatio().then(() {// console.log(即将上传的商品 JSON.stringify(this.product));uploadSellProduct(this.product).then(res {this.$refs.uToast.show({type: success,message: 您的商品已经发布到平台})setTimeout(() {uni.reLaunch({url: /pages/index/index})}, 1000)}).catch(error {console.log(error: JSON.stringify(error));this.$refs.uToast.show({type: error,message: 商品发布失败})});});}} else {this.$refs.uToast.show({type: error,message: 请选择分类})}},/*** 设置图片的宽高比*/setPicAspectRatio() {return new Promise((resolve, reject) {this.product.picList [];let promises [];for (let i 0; i this.picList.length; i) {let picUrl this.picList[i];promises.push(this.getAspectRatio(picUrl).then((res) {let pic {address: picUrl,aspectRatio: res}this.product.picList.push(pic);console.log(当前图片高宽比设置完成);}))}Promise.all(promises).then(() {console.log(所有图片高宽比设置完成this.product.picList: JSON.stringify(this.product.picList));resolve();})})},/*** 获取单个图片的高宽比* param {Object} url*/getAspectRatio(url) {return new Promise((resolve, reject) {uni.getImageInfo({src: url,success: function(res) {let aspectRatio res.height / res.width;resolve(aspectRatio);}});})},/*** 选择分类*/selectCategory() {uni.navigateTo({url: /pages/sellMyProduct/selectCategory})}}}
/scriptstyle langscss.container {background: #F6F6F6;min-height: 100vh;padding: 20rpx;.content {background: #ffffff;padding: 20rpx;.item {display: flex;align-items: center;height: 50px;margin-bottom: 5px;.labelName {width: 70px;margin-right: 10px;}.textClass {display: inline;background: #F7F7F7;padding: 10px;margin-right: 15px;border-radius: 5px;}.selectTextClass {display: inline;background: #2B92FF;padding: 10px;margin-right: 15px;border-radius: 5px;color: #ffffff;font-weight: bold;}.columnClass {// height: 50px;display: flex;align-items: center;width: calc(100% - 70px);overflow-x: auto;// // 让内容只有一行white-space: nowrap;}.columnClass::-webkit-scrollbar {background-color: transparent;/* 设置滚动条背景颜色 */// width: 0px;height: 0px;}}}}
/style