0


若依--文件上传前端

前端

ry的前端文件上传单独写了一个FileUpload.Vue文件。在main.js中进行了全局的注册,可以在页面中直接使用文件上传的组件。全局导入

在main.js中

  1. import 组件名称 from '@/components/FileUpLoad'
  2. app.compoent(组件名称) //全局挂载组件

在项目中使用

  1. 组件命令 中间有一个-。因为这是两个大写的单词拼接在一起的
  2. <el-form-item label="选择文件" prop="file">
  3. <file-upload v-model="fileData"/>
  4. </el-form-item>

对于上传FileUpload组件。

使用element-plus的el-upload组件

  1. <el-upload
  2. multiple 允许多个文件上传
  3. :action="uploadFileUrl" 上传的地址
  4. :before-upload="handleBeforeUpload" 在山川之间检查
  5. :file-list="fileList"
  6. :limit="limit"
  7. :on-error="handleUploadError"
  8. :on-exceed="handleExceed"
  9. :on-success="handleUploadSuccess"
  10. :show-file-list="false"
  11. :headers="headers" //请求头
  12. class="upload-file-uploader"
  13. ref="fileUpload" //拿到这个fileupload
  14. >
  15. //展示上传的文件列表
  16. <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
  17. <li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
  18. <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
  19. <span class="el-icon-document"> {{file.fileName}}</span>
  20. </el-link>
  21. <div class="ele-upload-list__item-content-action">
  22. <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
  23. </div>
  24. </li>
  25. </transition-group>

上传文件需要携带token。所以需要导入

  1. import { getToken } from "@/utils/auth";
  2. //请求头是键值对的形式
  3. const headers = ref({ Authorization: "Bearer " + getToken() });
  4. //上传组件绑定
  5. :headers="headers"

基本的方法包括 上传之前需要校验文件格式和大小、文件数量、成功回调函数、失败回调函数、删除文件、上传结束。

  1. defineProps

是 Vue 3 中的一个组合式 API,用于在组件中定义接收的 props。它允许你声明组件的属性及其类型和默认值,使得组件能够接收父组件传递的数据。具体功能如下:

定义父组件传过来的内容

  1. const props = defineProps({
  2. modelValue: [String, Object, Array],
  3. // 数量限制
  4. limit: {
  5. type: Number,
  6. default: 10,
  7. },
  8. // 大小限制(MB)
  9. fileSize: {
  10. type: Number,
  11. default: 100,
  12. },
  13. // 文件类型, 例如['png', 'jpg', 'jpeg']
  14. fileType: {
  15. type: Array,
  16. default: () => ["doc", "xls", "ppt", "txt", "pdf",'mp3'],
  17. },
  18. // 是否显示提示
  19. isShowTip: {
  20. type: Boolean,
  21. default: true
  22. }
  23. });

文件数据

  1. //上传的数据
  2. const uploadList = ref([]); //这个是每一次点击上传后的内容
  3. const fileList = ref([]); //所有的文件列表

上传成功回调函数

  1. function handleUploadSuccess(res, file) {
  2. if (res.code ==200) {
  3. //将后端返回的数据赋值给uploadlist数组
  4. uploadList.value.push({ fileName: res.data.fileName, url: res.data.url });
  5. uploadedSuccessfully();
  6. } else {
  7. number.value--;
  8. proxy.$modal.closeLoading();
  9. proxy.$modal.msgError(res.msg);
  10. proxy.$refs.fileUpload.handleRemove(file);
  11. uploadedSuccessfully();
  12. }
  13. }
  14. function uploadedSuccessfully() {
  15. if (number.value > 0 && uploadList.value.length === number.value) {
  16. //fileList 加上uploadlist
  17. fileList.value = fileList.value.concat(uploadList.value);
  18. //将filelist床穿给父组件
  19. emit("update:modelValue", fileList.value);
  20. proxy.$modal.closeLoading();
  21. uploadList.value = [];
  22. number.value = 0;
  23. }
  24. }

v-model的语法糖使用。

  1. emit 向父组件传递消息
  2. Vue 3 中,`v-model` 语法糖用于实现双向数据绑定,默认情况下,它实际上是通过发出 `update:modelValue` 事件与父组件进行通信的。
  3. ### 工作原理
  4. 1. **v-model 绑定**:
  5. - 当你在父组件中使用 `v-model="fileData"` 时,Vue 会自动将其转换为 `:modelValue="fileData"` `@update:modelValue="value => fileData = value"` 的组合。
  6. 2. **子组件的 emit**:
  7. - 在子组件中,调用 `emit("update:modelValue", fileList.value);` 会发出 `update:modelValue` 事件,并将当前的 `fileList.value` 作为新值传递。
  8. 3. **父组件接收更新**:
  9. - 父组件通过 `@update:modelValue` 监听这个事件,接收到的值会自动更新到 `fileData` 中,实现双向绑定。
  10. ### 总结
  11. 因此,使用 `v-model` 使得父组件能够方便地接收子组件通过 `emit("update:modelValue", ...)` 发送的数据更新,从而实现了更简洁的状态管理和组件通信。
  1. watch(() => props.modelValue, val => {
  2. if (Array.isArray(val) && val.length) {
  3. fileList.value = val.map(item => {
  4. return {
  5. fileName: item.fileName || item,
  6. url: item.url || item,
  7. // uid: item.uid || new Date().getTime()
  8. uid: item.uid || new Date().getTime()
  9. };
  10. });
  11. } else {
  12. fileList.value = [];
  13. }
  14. }, { deep: true, immediate: true });
  15. 这段代码使用 Vue 3 `watch` API 来监视 `props.modelValue` 的变化,并根据这个变化更新 `fileList`。具体来说,它的功能如下:
  16. ### 代码分析
  17. 1. **监视 `props.modelValue`**:
  18. ```javascript
  19. watch(() => props.modelValue, val => { ... }, { deep: true, immediate: true });
  • () => props.modelValue:这是一个计算属性,用于获取 modelValue 的值。
  • val:当 modelValue 发生变化时,这个回调函数将被调用,val 是新的值。
  1. 判断类型和内容if(Array.isArray(val)&& val.length){...}else{ fileList.value =[];}- 检查 val 是否是一个数组且非空。如果是,执行下一步;否则,将 fileList.value 设置为空数组。
  2. **映射 fileList**:fileList.value = val.map(item=>{...});- 使用 map 方法遍历 val 数组,将每个元素转换为一个对象,包含 fileNameurluid。如果 item 没有提供 fileNameurl,则使用 item 本身。
  3. 选项:- { deep: true }:如果 modelValue 是一个嵌套对象,深度监视将确保任何内部属性的变化也会触发回调。- { immediate: true }:在组件初始挂载时立即调用回调,以便在初始渲染时更新 fileList

总结

这段代码的主要作用是确保当

  1. modelValue

更新时,

  1. fileList

也会随之更新,从而保持两个数据状态的一致性。如果

  1. modelValue

是一个有效的数组,

  1. fileList

将根据其内容进行填充;如果不是,

  1. fileList

将被清空。这种方式适用于处理上传文件列表或类似的场景。


本文转载自: https://blog.csdn.net/ngczx/article/details/142654091
版权归原作者 全栈阿星 所有, 如有侵权,请联系我们删除。

“若依--文件上传前端”的评论:

还没有评论