微信小程序开发中,瀑布流布局和图片懒加载是比较常见的需求。下面我将给出一个完整的代码案例,详细解释如何实现瀑布流布局和图片懒加载。
-
创建项目并配置小程序基本信息 首先,我们需要在微信开发者工具中创建一个新的小程序项目。在项目目录下找到
app.json
文件,配置小程序的基本信息,包括标题、顶部背景色等。 -
创建瀑布流组件 在项目的根目录下新建一个
components
文件夹,并在其中创建一个waterfall
文件夹。在waterfall
文件夹下创建waterfall.wxml
、waterfall.wxss
和waterfall.js
文件。
2.1 waterfall.wxml
<view class="waterfall">
<block wx:for="{{list}}" wx:key="index">
<view class="item" bindtap="handleItemClick" data-index="{{index}}">
<image class="img" src="{{item.src}}" mode="aspectFill"></image>
<view class="desc">{{item.desc}}</view>
</view>
</block>
</view>
2.2 waterfall.wxss
.waterfall {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.item {
width: 48%;
margin-bottom: 10px;
background-color: #f5f5f5;
border-radius: 5px;
padding: 10rpx;
box-sizing: border-box;
position: relative;
}
.img {
width: 100%;
border-radius: 5px;
}
.desc {
margin-top: 10px;
}
2.3 waterfall.js
Component({
properties: {
list: {
type: Array,
value: []
}
},
methods: {
handleItemClick(e) {
const index = e.currentTarget.dataset.index;
const item = this.data.list[index];
// 处理点击事件
}
}
})
- 在页面中使用瀑布流组件 在我们需要使用瀑布流布局的页面中引入组件。在页面的
.wxml
文件中添加以下代码:
<waterfall list="{{list}}"></waterfall>
- 实现图片懒加载 为了实现图片懒加载,我们需要使用小程序提供的
IntersectionObserver
API 监听图片是否进入可视区域。具体实现如下:
4.1 在 onLoad
函数中初始化 IntersectionObserver 实例,并监听图片的显示和隐藏事件。
Page({
data: {
list: []
},
onLoad() {
const observer = wx.createIntersectionObserver(this);
observer.relativeToViewport().observe('.img', (res) => {
const { intersectionRatio, intersectionRect } = res;
if (intersectionRatio > 0 && intersectionRect.bottom >= 0) {
const index = res.dataset.index;
// 图片进入可视区域,加载图片
this.loadImage(index);
}
});
},
loadImage(index) {
// 加载图片的具体实现逻辑
}
})
4.2 在 loadImage
函数中实现图片的懒加载逻辑。
loadImage(index) {
const item = this.data.list[index];
const imgKey = `list[${index}].loaded`;
const imgSrc = `list[${index}].src`;
wx.getImageInfo({
src: item.src,
success: (res) => {
this.setData({
[imgSrc]: res.path,
[imgKey]: true
});
},
fail: (err) => {
console.error(err);
}
});
}
- 数据加载和刷新 在实际应用中,我们往往需要从服务器获取数据并进行瀑布流布局和图片懒加载。这里以请求接口获取数据的方式为例,模拟数据的加载和刷新。具体实现如下:
Page({
data: {
list: [],
page: 1,
pageSize: 10,
loading: false,
finished: false
},
onLoad() {
this.loadData();
},
loadData() {
if (this.data.loading || this.data.finished) {
return;
}
this.setData({
loading: true
});
wx.request({
url: 'http://your-api.com/data', // 修改为实际接口地址
data: {
page: this.data.page,
pageSize: this.data.pageSize
},
success: (res) => {
const data = res.data;
const list = this.data.list.concat(data);
this.setData({
list,
page: this.data.page + 1,
loading: false,
finished: data.length < this.data.pageSize
});
},
fail: (err) => {
console.error(err);
this.setData({
loading: false
});
}
});
},
refreshData() {
this.setData({
list: [],
page: 1,
finished: false
});
this.loadData();
}
})
至此,我们已经完成了微信小程序中瀑布流布局和图片懒加载的实现。希望以上代码案例能对你有所帮助。如果有任何疑问,可以随时向我提问。