做项目时用户总说图片不能保存?一行代码实现图片预览,长按还能保存到相册,安排!
🎯 实现代码
html
预览
xml
<!-- template 里写图片列表 -->
<view class="img-list">
<image
v-for="(item, index) in imgList"
:key="index"
:src="item"
class="img-item"
@click="previewImg(index)"
></image>
</view>
javascript
运行
javascript
export default {
data() {
return {
// 图片列表,换成你的图片地址
imgList: [
"https://xxx.com/img1.jpg",
"https://xxx.com/img2.jpg",
"https://xxx.com/img3.jpg"
]
};
},
methods: {
// 预览图片
previewImg(current) {
uni.previewImage({
current: current, // 当前点击的图片索引
urls: this.imgList, // 所有要预览的图片列表
longPressActions: {
// 长按显示的操作菜单
itemList: ["保存图片", "分享图片"],
success: (res) => {
if (res.tapIndex === 0) {
// 点击保存图片
this.saveImg(this.imgList[current]);
}
}
}
});
},
// 保存图片到相册
saveImg(imgUrl) {
uni.saveImageToPhotosAlbum({
filePath: imgUrl,
success: () => {
uni.showToast({
title: "保存成功",
icon: "success"
});
},
fail: (err) => {
// 用户拒绝授权时提示
if (err.errMsg.includes("auth deny")) {
uni.showToast({
title: "请开启保存图片权限",
icon: "none"
});
}
}
});
}
}
};
🎨 加个简单样式
css
css
.img-list {
display: flex;
flex-wrap: wrap;
gap: 10rpx;
padding: 20rpx;
}
.img-item {
width: 30%;
height: 200rpx;
border-radius: 8rpx;
}
💡 权限提醒:保存图片需要用户授权,第一次点击会弹出授权提示,记得引导用户允许!