vue+antd上传组件(Upload)的简单案例

本文介绍如何在Vue项目中结合Ant Design的Upload组件实现文件上传功能,包括文件验证、覆盖提醒及状态反馈。通过创建upload.vue组件并编写相应代码,详细展示了Upload组件的使用方法。

概要:使用antd的Upload组件自定义上传功能,包含上传、文件验证、回传(成功/失败);

步入正题:

1、创建upoload.vue,编写demo代码:

<template>
  <a-modal
    v-model="visible"
    centered
    :mask-closable="false"
    :width="480"
    :footer="null"
    @cancel="hideModal"
  >
    <div class="outer">
      <div v-if="uploadStep==='upload'">
        <p class="uploadTitle">
          上传文件
        </p>
        <p>
          本地上传 Excel 文件
        </p>
        <p>
          不符合格式的Excel会导致上传失败
        </p>
        <a-upload
          name="file"
          :action="uploadUrl"
          :show-upload-list="false"
          @change="checkFile"
        >
          <a-button
            type="primary"
          >
            <a-icon type="upload" />上 传
          </a-button>
        </a-upload>
        <p>
          <span>或</span>
        </p>
        <a-button
          type="link"
          icon="download"
          @click="downloadTemplate"
        >
          下载模板
        </a-button>
      </div>
      <div v-if="uploadStep==='cover'">
        <img
          class="uploadIco1"
          src="@assets/images/waiting.png"
        >
        <p>
          请确认是否覆盖?
        </p>
        <p>
          点击“确定”继续上传,点击“取消”中断上传
        </p>
        <div>
          <a-button @click="handleRestart">
            取消
          </a-button>
          <a-button
            type="primary"
            @click="handleCover"
          >
            确定
          </a-button>
        </div>
      </div>
      <div v-if="uploadStep==='loading'">
        <a-icon
          type="loading"
          class="uploading"
        />
      </div>
      <div v-if="uploadStep==='success'">
        <img
          class="uploadIco1"
          src="@assets/images/success.png"
        >
        <div>
          上传成功!<br>正在自动跳转...
        </div>
        <div>
          跳转倒计时:{{ CountDown }}秒
        </div>
      </div>
      <div v-if="uploadStep==='fail'">
        <img
          class="uploadIco2"
          src="@assets/images/fail.png"
        >
        <p>
          {{ failMessage }}
        </p>
        <a-upload
          name="file"
          :action="uploadUrl"
          :show-upload-list="false"
          @change="checkFile"
        >
          <a-button type="primary">
            重新上传
          </a-button>
        </a-upload>
        <p>
          <span>或</span>
        </p>
        <a-button
          type="link"
          icon="download"
          @click="downloadTemplate"
        >
          下载模板
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

2、按需引入antd的组件,定义常量:

<script>
import Vue from 'vue'
import { Modal, Button, Icon, Upload } from 'ant-design-vue'

Vue.use(Modal)
Vue.use(Button)
Vue.use(Icon)
Vue.use(Upload)

// 上传组件
export default {
  name: 'Upload',
  data() {
    return {
      visible: false,
      uploadStep: '',
      uploadUrl: '',
      failMessage: '',
      CountDown: '',
    }
  },
}

3、调用的方法以及交互逻辑代码(验证文件、是否覆盖已有文件、状态返回)

methods: {
    showModal(){
        this.visible = true;
        this.uploadStep = 'upload'
    },
    hideModal(){
        this.visible = false;
        // 为了体验效果,这里可以增加延时代码
        this.uploadStep = ''
    },
    // 点击下载模板
    downloadTemplate() {
      const a = document.createElement('a')
      a.href = 'url' //url=模版详细地址,此处仅用“url“代替详细地址的具体内容
      a.target = '_blank'
      a.click()
    },
    // 校验excel
    async checkFile(info) {
      // 符合返回成功和解析的json数据(二次上传),不符合返回报错信息,重新上传
      if (info.file.status === 'done') {
        const result = info.file.response
        if (!result.status) {
          this.failMessage = result.message
          this.uploadStep = 'fail'
        } else {
          if (!result.cover) {
            let timeout = null
            clearTimeout(timeout)
            this.uploadStep = 'loading'
            timeout = setTimeout(() => {
              this.upload()
            }, 1000)
          } else {
            this.uploadStep = 'cover'
          }
        }
      } else if (info.file.status === 'error') {
        // 网络异常报错
        this.failMessage = '网络错误'
        this.uploadStep = 'fail'
      }
    },
    // 校验通过,创建或覆盖原数据
    async upload() {
      try {
        await //此处增加接口请求,上传文档或数据
        // 上传成功 3秒倒计时 跳转
        this.uploadStep = 'success'
        const TIME_COUNT = 3
        this.CountDown = TIME_COUNT
        this.timer = setInterval(() => {
          if (this.CountDown > 1 && this.CountDown <= TIME_COUNT) {
            this.CountDown--
          } else {
            clearInterval(this.timer)
            this.timer = null
            // 跳转的页面写在此处
            this.$router.replace({
                name: 'uploadFilesPage',
            })
          }
        }, 1000)
      } catch (error) {
        // 网络异常报错
        const msg = error.errorMessage || error.message || '网络错误'
        this.failMessage = msg
        this.uploadStep = 'fail'
      }
    },
    // 覆盖原文件
    handleCover() {
      let timeout = null
      clearTimeout(timeout)
      this.uploadStep = 'loading'
      timeout = setTimeout(() => {
        this.upload()
      }, 1000)
    },
    // 点击取消,返回伤处初始界面
    handleRestart() {
      this.uploadStep = 'upload'
    },

}

  本文是对upload组件的简单使用过程,代码拿来即用,希望能起到一个抛砖引玉的作用。感谢阅读!

 

在前端使用VueAntD和Axios访问后端四个API,可参考以下步骤及示例代码。 ### 1. 项目初始化与依赖安装 确保已安装VueAntD,若未安装,可通过以下命令创建Vue项目并安装AntD和Axios: ```bash npm init vite@latest my-vue-app -- --template vue cd my-vue-app npm install antd axios ``` ### 2. 引入AntD组件和Axios 在 `main.js`(Vue 2)或 `main.ts`(Vue 3)中引入AntD组件和CSS文件,同时可配置Axios: ```javascript // main.js (Vue 2) import Vue from 'vue'; import App from './App.vue'; import { Button, Card } from 'ant-design-vue'; import 'ant-design-vue/dist/antd.css'; import axios from 'axios'; Vue.use(Button); Vue.use(Card); Vue.prototype.$axios = axios; Vue.config.productionTip = false; new Vue({ render: h => h(App), }).$mount('#app'); ``` ```javascript // main.ts (Vue 3) import { createApp } from 'vue'; import App from './App.vue'; import Antd from 'antd'; import 'antd/dist/antd.css'; import axios from 'axios'; const app = createApp(App); app.use(Antd); app.config.globalProperties.$axios = axios; app.mount('#app'); ``` ### 3. 编写访问API的代码 在组件中使用Axios访问后端的四个API,以下是一个示例: ```vue <template> <div> <a-button @click="fetchData">Fetch Data</a-button> <a-card v-if="data1" title="API 1 Data">{{ data1 }}</a-card> <a-card v-if="data2" title="API 2 Data">{{ data2 }}</a-card> <a-card v-if="data3" title="API 3 Data">{{ data3 }}</a-card> <a-card v-if="data4" title="API 4 Data">{{ data4 }}</a-card> </div> </template> <script setup> import { ref } from 'vue'; const data1 = ref(null); const data2 = ref(null); const data3 = ref(null); const data4 = ref(null); const fetchData = async () => { try { const response1 = await this.$axios.get('http://backend-api-url/api1'); data1.value = response1.data; const response2 = await this.$axios.get('http://backend-api-url/api2'); data2.value = response2.data; const response3 = await this.$axios.get('http://backend-api-url/api3'); data3.value = response3.data; const response4 = await this.$axios.get('http://backend-api-url/api4'); data4.value = response4.data; } catch (error) { console.error('Error fetching data:', error); } }; </script> ``` ### 4. 错误处理与优化 在实际应用中,需要对API请求进行错误处理,可使用 `try...catch` 语句捕获异常。同时,可添加加载状态和重试机制等优化措施。
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值