该组件用于上传图片场景
App(vue) | App(nvue) | H5 | 小程序 |
---|---|---|---|
√ | √ | √ | √ |
fileList
参数(数组,元素为对象),显示预置的图片。其中元素的url
属性为图片路径<template>
<u-upload
:fileList="fileList1"
@afterRead="afterRead"
@delete="deletePic"
name="1"
multiple
:maxCount="10"
></u-upload>
</template>
<script>
export default {
data() {
return {
fileList1: [],
}
},
methods:{
// 删除图片
deletePic(event) {
this[`fileList${event.name}`].splice(event.index, 1)
},
// 新增图片
async afterRead(event) {
// 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式
let lists = [].concat(event.file)
let fileListLen = this[`fileList${event.name}`].length
lists.map((item) => {
this[`fileList${event.name}`].push({
...item,
status: 'uploading',
message: '上传中'
})
})
for (let i = 0; i < lists.length; i++) {
const result = await this.uploadFilePromise(lists[i].url)
let item = this[`fileList${event.name}`][fileListLen]
this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
status: 'success',
message: '',
url: result
}))
fileListLen++
}
},
uploadFilePromise(url) {
return new Promise((resolve, reject) => {
let a = uni.uploadFile({
url: 'http://192.168.2.21:7001/upload', // 仅为示例,非真实的接口地址
filePath: url,
name: 'file',
formData: {
user: 'test'
},
success: (res) => {
setTimeout(() => {
resolve(res.data.data)
}, 1000)
}
});
})
},
}
}
</script>
copy
accept='video'
属性,将上传改为视频上传。<u-upload
:fileList="fileList2"
@afterRead="afterRead"
@delete="deletePic"
name="2"
multiple
:maxCount="10"
accept="video"
></u-upload>
<!-- data 方法请参考 基本用法 -->
data(){
return{
fileList2: [],
}
}
copy
:previewFullImage="true"'
属性,达到文件预览的目的。<u-upload
:fileList="fileList3"
@afterRead="afterRead"
@delete="deletePic"
name="3"
multiple
:maxCount="10"
:previewFullImage="true"
></u-upload>
<!-- data 方法请参考 基本用法 -->
data(){
return{
fileList3: [{
url: 'https://cdn.uviewui.com/uview/swiper/1.jpg',
}],
}
}
copy
maxCount
所规定的数据时,隐藏上传按钮。<u-upload
:fileList="fileList4"
@afterRead="afterRead"
@delete="deletePic"
name="4"
multiple
:maxCount="2"
></u-upload>
<!-- data 方法请参考 基本用法 -->
data(){
return{
fileList4: [{
url: 'https://cdn.uviewui.com/uview/swiper/1.jpg',
},
{
url: 'https://cdn.uviewui.com/uview/swiper/1.jpg',
}
],
}
}
copy
maxCount
的数据时。<u-upload
:fileList="fileList5"
@afterRead="afterRead"
@delete="deletePic"
name="5"
multiple
:maxCount="3"
></u-upload>
<!-- data 方法请参考 基本用法 -->
data(){
return{
fileList5: [],
}
}
copy
image
以自定义上传样式,达到身份证,银行卡等不同场景需求。<u-upload
:fileList="fileList6"
@afterRead="afterRead"
@delete="deletePic"
name="6"
multiple
:maxCount="1"
width="250"
height="150"
>
<image src="https://cdn.uviewui.com/uview/demo/upload/positive.png"
mode="widthFix" style="width: 250px;height: 150px;"></image>
</u-upload>
<!-- data 方法请参考 基本用法 -->
data(){
return{
fileList6: [],
}
}