vue3+uniapp 上傳附件的操作代碼
uni-file-picker搭配uni.uploadFile在使用問題上踩了不少坑,我至今還是沒辦法在不改uniapp源碼基礎(chǔ)上實現(xiàn)限制重復(fù)文件的上傳。因為始終怎么限制,uni-file-picker綁定的v-model的值fileList,好像只要上傳了文件展示就一定會回顯那一個附件。還有一個問題,就是上傳的進度條并不能正常工作。直接css隱藏算了眼不見心不煩
多次試圖馴服該組件,發(fā)現(xiàn)如果要把上傳好的文件列表同步給父組件,就不要去傳組件綁定的value值,因為這會出問題,把這個變量當做單純展示的作用就好了,父子組件的數(shù)據(jù)傳輸,可以用雙向綁定,文件的增刪改都操作這個雙向綁定的數(shù)據(jù)。
子組件:封裝的文件上傳
c-upload.vue
<template>
<uni-file-picker
v-model="fileList"
:auto-upload="false"
file-mediatype="all"
mode="grid"
@delete="delFile"
@select="select"
>
<text class="iconfont icon-zengjiatianjiajiahao"></text>
</uni-file-picker>
</template>
<script setup>
import {ref, reactive, watch} from "vue";
const props = defineProps({
appendixEntityList: {default: []},
});
const emit = defineEmits(["update:appendixEntityList"]);
let fileList = ref([]);
// 選擇上傳觸發(fā)函數(shù)
const select = (e) => {
// 根據(jù)所選圖片的個數(shù),多次調(diào)用上傳函數(shù)
let promises = [];
for (let i = 0; i < e.tempFilePaths.length; i++) {
const promise = uploadFiles(e.tempFilePaths, i);
promises.push(promise);
}
Promise.all(promises).then(() => {
});
};
// 上傳函數(shù)
const uploadFiles = async (tempFilePaths, i) => {
await uni.uploadFile({
url: '/api/xxx/xxxx/xxxx', //后端用于處理圖片并返回圖片地址的接口
filePath: tempFilePaths[i],
name: "file",
header: {
Authorization: "Bearer " + uni.getStorageSync("token") || "",
ContentType: "application/x-www-form-urlencoded",
skipToken: true,
},
success: (res) => {
let v = JSON.parse(res.data); //返回的是字符串,需要轉(zhuǎn)成對象格式
if (v.code == 200) {
props.appendixEntityList.push({
appendixId: v.data.id,
appendixOriginal: v.data.original,
appendixUrl: v.data.attachUrl,
});
emit("update:appendixEntityList", props.appendixEntityList);
}
},
fail: () => {
console.log("err");
},
});
};
//文件列表回顯
const fileListEcho = () => {
if (props.appendixEntityList.length > 0) {
fileList.value = [];
props.appendixEntityList?.forEach((v) => {
//改成官方文檔要求的格式。才能回顯附件
fileList.value.push({
name: v?.appendixOriginal,
extname: v?.appendixType,
url: v?.appendixUrl,
});
});
}
};
// 移出圖片函數(shù)
const delFile = async (val) => {
//在提交數(shù)組中刪除那個被刪的文件
props.appendixEntityList.some((v, i) => {
if (v.appendixOriginal === val.tempFile.name) {
props.appendixEntityList.splice(i, 1);
emit("update:appendixEntityList", props.appendixEntityList);
return true;
}
});
};
watch(
() => props.appendixEntityList,
(newVal) => {
fileListEcho();
},
);
</script>
<style lang="scss" scoped>
.icon-zengjiatianjiajiahao {
font-size: 42rpx;
color: #a2a3a5;
position: absolute;
right: 0;
top: -50rpx;
}
</style>父組件:
<!-- 上傳-->
<c-upload
ref="uploadRef"
v-model:appendixEntityList="form.appendixEntityList"
></c-upload>到此這篇關(guān)于vue3+uniapp 上傳附件的文章就介紹到這了,更多相關(guān)vue3+uniapp 上傳附件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3使用Proxy構(gòu)建高效響應(yīng)式數(shù)據(jù)的示例代碼
在 Vue 3 中,Proxy 主要用于 攔截對象的基本操作,包括 屬性讀取(get)、修改(set)、刪除(deleteProperty) 等,本文給大家介紹了Vue3使用Proxy構(gòu)建高效響應(yīng)式數(shù)據(jù)的操作教程,需要的朋友可以參考下2025-03-03

