<!--子组件-->
<template>
<view>
<view class="content">
<view class="imageBigBox" v-for="(item,i) in imageList" :key="i">
<image style="width: 100%;height: 160rpx;" @click="previewImg(item)" :src="item"></image>
<u-icon class="delIcon" name="close-circle" color="#999" size="25" @click="delectImg(i)"></u-icon>
</view>
<view class="flex-center upImg" v-if="imageList.length<maxCount" @click="chooseFile">
<u-icon name="camera-fill" color="#c1c1c1" size="30"></u-icon>
</view>
</view>
</view>
</template>
<script>
export default {
name: "rc-upload-img",
props: {
//上传图片最大数量
maxCount: {
type: Number,
default: 1
},
},
data() {
return {
BASE_URL: getApp().globalData.BASE_URL,//请求服务器域名如: https://www.XXX.com
imageList: [],//本地上传图片数组
list: [],//上传后端后返回的图片链接数组
};
},
methods: {
//上传图片
async chooseFile() {
uni.chooseImage({
count: this.maxCount - this.imageList.length,//图片大于1可以多选,这样可以不超出最大上传值
sourceType: ['album'],
success: (res) => {
this.list=[]
res.tempFilePaths.forEach(item => {
this.imageList.push(item)
})
this.imageList.forEach(item => {
this.upImg(item)
})
// console.log(res, "res", this.imageList)
}
});
},
//图片数据上传后端
upImg(path) {
uni.uploadFile({
url: `${this.BASE_URL}/api/common/upload`,
filePath: path,
name: 'file',
success: (res) => {
const data=eval('('+res.data+')')
if(data.code==1){
this.list.push(data.data.url)
this.$emit('list', this.list); //通知父组件有图片更新
}
// console.log('上传:', this.list,data, );
}
});
},
//删除图片
delectImg(i) {
uni.showModal({
title: '提示',
content: '确定要删除照片吗?',
cancelText: '取消',
confirmText: '确定',
success: res => {
if (res.confirm) {
this.imageList.splice(i, 1)
this.list.splice(i,1)
this.$emit('list', this.list); //通知父组件删除了数据
}
}
})
},
//点击预览图片
previewImg(current) {
uni.previewImage({
current,
urls: this.imageList,//存放图片的数组
loop: true,
indicator: "default"
})
},
}
}
</script>
<style lang="scss" scoped>
.upImg {
width: 100%;
height: 160rpx;
background: #f4f5f7;
}
.content {
margin-right: 10rpx;
display: grid;
grid-template-columns: repeat(4, 24%);
grid-gap: 20rpx;
}
.imageBigBox {
position: relative;
}
.delIcon {
position: absolute;
right: 0;
top: -16rpx;
}
</style>
<!--父组件使用: 如果组件是遵循uniapp 组件开发命名的,pages.json里面配置了可以直接使用,不是的话要将组件引入使用页面-->
<rc-upload-img :maxCount="1" @list="getImgList"></rc-upload-img>
<script>
data(){
return{
photoList :[]
}},
methods: {
getImgList(e) {
this.photoList = e
},
}
</script>
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。