概述
实现效果
实现思路
1.从接口获取数据后,将数据分为两组,左右各为一组数据。
2.图片的宽度固定,只需要计算图片的高度即可,由于接口返回的数据没有图片的宽高,所以要通过计算图片的高
计算公式:固定的宽度/图片的宽度*图片的高度
3.然后通过比较左右两边(数据列表)的高度,来确定下一张图片放在哪边
先说一下遇到的坑wx.getImageInfo()
实现的效果:顺序是不对的
每次刷新顺序都会变,原因wx.getImageInfo()是异步的方法
解决的方法,就是对wx.getImageInfo()进行封装,封装成promise,实现异步方法的同步化
getImageInfo(src) {
return new Promise((resolve, reject) => {
wx.getImageInfo({
src,
success(res) {
const height = res.height * 750 / res.width
resolve({ ...res,
height,
src
})
},
fail(e) {
console.error(e)
//获取图片高度失败时自动填充750
reject({
type:'error',
height: 750,
src
})
}
})
})
},
实现瀑布流详细代码
.talentBlock_box{
width: 690rpx;
margin: 0 auto;
}
.talentBlock_left{
float: left;
margin-right: 20rpx;
}
.talentBlock_rigft{
float: right;
}
.talentBlock {
width: 330rpx;
margin-bottom: 40rpx;
}
<!-- 其他内容自己调 -->
<view class="talentBlock_box">
<view class="talentBlock_left">
<view class="talentBlock" wx:for="{{talentLeft}}" wx:for-index="f_index"></view>
</view>
<view class="talentBlock_rigft">
<view class="talentBlock" wx:for="{{talentRight}}" wx:for-index="f_index"></view>
</view>
</view>
//调接口成功后
success: function(t) {
//t接口获取的数据 talentList包含图片和内容 picList图片列表
var width=165,height=71,talentList=t.data ,picList=[],leftHeight=0,rightHeight=0,leftList=[],rightList=[]
//width宽固定 height为标题和个人信息的高度 leftList左边栏的数据 rightList右边栏的数据
for (let i = 0; i < talentList.length; i++) {
//先将图片抽离出来单独处理
picList.push(n+talentList[i].img[0])
}
let loadPicPs=[]
console.log(picList);
for(let i=0;i<picList.length;i++){
//这里的e是this getImageInfo为
loadPicPs.push(e.getImageInfo(picList[i]))
}
Promise.all(loadPicPs).then(res => {
console.log(res);
for (let i = 0; i < res.length; i++) {
let imgHeight=Math.round(width/res[i].width*res[i].height)+height
if(leftHeight<=rightHeight){
leftList.push(talentList[i])
leftHeight+=imgHeight
}else{
rightList.push(talentList[i])
rightHeight+=imgHeight
}
e.setData({
talentLeft: leftList, //需要渲染的数据
talentRight:rightList, //需要渲染的数据
url: n, //后三项是项目中用到的,不用管,page 页码需要的自己配置
page: 1,
activeIndex: 0
});
}
})
不要忘了上面封装的wx.getImageInfo()
这样就可以实现瀑布流了
本文参考
https://developers.weixin.qq.com/community/develop/article/doc/000a2e9db9ca98a3c379cfa4a5d013
最后
以上就是迅速世界为你收集整理的微信小程序瀑布流实现及遇到的坑的全部内容,希望文章能够帮你解决微信小程序瀑布流实现及遇到的坑所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复