vue+ElementUI开发公共导入、下载模版组件_上传

弹出框组件

<template>
    <el-dialog :title="upload.title" :visible.sync="visible" width="400px" append-to-body :close-on-click-modal="false" :before-close="close" @close="onClose">
        <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :data="updata"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" 
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">{{$t('formValidation.dragFilesHere')}} {{$t('formValidation.or')}}<em>{{$t('formValidation.clickToUpload')}}</em></div>
            <div class="el-upload__tip text-center" slot="tip">
                
                <span>{{$t('formValidation.onlyXlsXlsx')}}</span>
                <a @click="downloadTemplate" style="font-size:12px;vertical-align: baseline;color:#1890ff">{{ $t('formValidation.downloadTemplate') }}</a>
                
            </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
            <el-button @click="close" icon="el-icon-close" size="small">{{$t('btn.cancel')}}</el-button>
            <el-button type="primary" :loading="loading" @click="submitFileForm" icon="el-icon-check" size="small">{{$t('btn.confirm')}}</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { getItemsByTemplateName } from '@/api/inspectionManagement'
 import { ACCESS_TOKEN } from '@/store/mutation-types'
export default {
    name: 'TemplateDialog',
    props: {
        visible: {
            type: Boolean,
            default: false,
        },
        params: {
            type: Object,
            default: null,
        },
        action: {
            type: String,
            default: "",
        },
        templateUrl: {
            type: String,
            default: null,
        },
        fileName: {
            type: String,
            default: `template_${new Date().getTime()}`,
        },
    },
  watch: {
    // 监听 propName 的变化
    action(newVal) {
      // 在这里可以执行相应的操作,比如更新子组件的状态等
      this.uploadUrl =  newVal 
    }
  },
    data() {
        return {
            updata:{},
            uploadUrl:'',
            total: 1,
            templateList: [{ templateName: 'xx模板' }],
            // 用户导入参数
            upload: {
                // 是否显示弹出层(用户导入)
                open: false,
                // 弹出层标题(用户导入)
                title: this.$t('btn.import'),
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { 'X-Access-Token':   this.$ls.get(ACCESS_TOKEN)},
                // 上传的地址
                url: process.env.VUE_APP_API_BASE_URL + this.action,
            },
            loading: false,
            data: null,
            title: '',
           
        }
    },
    methods: {
        
        downloadTemplate() {
            let a = document.createElement('a')
            a.href ='http://xxxx.xxx.xx/xxx/templates/'+this.templateUrl
            a.download = `${this.fileName}.xlsx`
            a.style.display = 'none'
            document.body.appendChild(a)
            a.click()
            a.remove()
              
        },
        // 提交上传文件
        submitFileForm() {
            this.loading = true
            this.$refs.upload.submit()
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            if (response.code === 200) {
                this.loading = false
                this.upload.open = false
                this.upload.isUploading = false
                this.$refs.upload.clearFiles()
                this.$emit('callback', true)
                this.$emit('update:visible', false)
                this.$alert(response.message?response.message:response.msg, '导入结果', {
                    dangerouslyUseHTMLString: true,
                })
            } else {
                this.loading = false
                this.$modal.msgError(response.message?response.message:response.msg)
                this.upload.open = false
                this.upload.isUploading = false
                this.$refs.upload.clearFiles()
                this.$emit('update:visible', false)
            }
        },
        // 窗口关闭
        onClose() {
            this.$emit('update:visible', false)
        },
        handleConfirm() {
            this.$emit('update:visible', false)
        },
        choose(scope) {
            console.log(scope.row.templateName)
            getItemsByTemplateName({
                templateName: scope.row.templateName,
            }).then((response) => {
                console.log(response)
            })
        },
        // 窗口关闭前执行
        close() {
            this.$emit('update:visible', false)
        },
    },
}
</script>

<style scoped>
::v-deep .el-dialog__footer {
    text-align: center;
}
.search-btn {
    background: #20b09f;
    border-color: #20b09f;
}
</style>

使用组件

vue+ElementUI开发公共导入、下载模版组件_上传_02

技术栈简介

  • Vue.js:前端框架,用于构建用户界面。
  • Element UI:一套为Vue.js设计的桌面端组件库,提供了丰富的UI组件。

核心知识点

  1. 模板语法
  • 使用<template>标签定义组件的HTML结构。
  • 结合Vue指令(如:titlev-model@click)动态绑定数据和事件处理。
  1. 组件通信
  • Props:父组件向子组件传递数据,如visibleparamsaction等。
  • $emit:子组件通过触发自定义事件(如update:visible)通知父组件。
  1. Element UI组件使用
  • el-dialog:创建一个模态对话框,通过:visible.sync控制显示隐藏,:append-to-body让对话框脱离当前文档流。
  • el-upload:实现文件上传功能,设置accept限制上传文件类型,:action指定上传地址,:on-success定义上传成功后的回调。
  • el-button:按钮组件,:loading属性控制加载状态,:icon添加图标。
  1. 数据绑定与方法定义
  • data():初始化组件状态,如uploadUrlupload对象等。
  • methods:定义组件行为,如submitFileForm提交上传,handleFileSuccess处理上传成功逻辑,downloadTemplate下载模板。
  1. 动态计算与条件渲染
  • 使用表达式(如{{$t('formValidation.dragFilesHere')}})进行国际化文本渲染。
  • v-ifv-model未直接展示,但理解它们在Vue中对于条件渲染和双向数据绑定的重要性。
  1. API调用
  • 引入并使用API方法(如listTemplategetItemsByTemplateName)进行后端交互,获取或处理数据。
  1. 响应式编程
  • watch:监听action属性的变化,自动更新uploadUrl以适应动态上传地址需求。
  1. 样式定制
  • 使用<style scoped>进行组件内样式隔离,以及:deep()(或::v-deep)穿透符来影响子组件样式。

技巧总结

  • 拖拽上传:通过drag属性启用el-upload组件的拖拽上传功能。
  • 国际化支持:利用Vue的插值表达式结合翻译函数(如$t)实现界面多语言。
  • 动态表单行为:根据上传状态(如upload.isUploading)动态禁用按钮或显示进度提示。
  • 文件下载:通过JavaScript动态创建<a>标签并模拟点击事件实现文件下载,无需服务器额外配置。
  • 事件处理与状态管理:合理利用Vue的生命周期钩子(如before-close)和事件处理器管理组件状态与用户交互。