index.vue 1.77 KB
<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
// import * as store from "@/pinia/index";
import { useLoginStore } from '@/pinia/login';
const upload = ref();
/**
 * @description 组件属性
 * @prop {string | null} url 上传地址
 * @prop { string | null } method 上传请求方法
 *
 */
interface Props {
  url: string;
  method: string;
}
const props = withDefaults(defineProps<Props>(), {});
const emit = defineEmits<{
  (e: "success"): void;
}>();
/**
 * @description 上传配置
 */
const setting = reactive({
  url: `${import.meta.env.VITE_BASE_URL}${props.url}`,
  headers: {
    // "X-Token": store.family.loginStore().token,
    "X-Token": useLoginStore()?.getToken,
  },
  loading: false,
});
/**
 * 上传文件成功回调
 * @param { ElUploadProgressEvent } 回调返回对象
 */
const handleSuccess = (res: ElUploadProgressEvent) => {
  setting.loading = false;
  if (res.errorCode == 0) {
    ElMessage.success("操作成功");
    emit("success");
  } else {
    ElMessage.error(res.errorMessage ?? "操作失败");
  }
};

/**
 * 上传文件失败回调
 * @param { ElUploadProgressEvent } 回调返回对象
 */
const handlError = (err: ElUploadProgressEvent) => {
  console.log(err);
};
/**
 * 文件上传中回调
 *
 */
const handleProgress = () => {
  setting.loading = true;
};
</script>
<template>
  <el-upload
    ref="upload"
    :action="setting.url"
    :headers="setting.headers"
    :method="props.method"
    accept=".xlsx,.xls"
    name="multipartFile"
    :with-credentials="true"
    :show-file-list="false"
    :on-success="handleSuccess"
    :on-error="handlError"
    :on-progress="handleProgress"
  >
    <el-button type="primary" :loading="setting.loading">导入</el-button>
  </el-upload>
</template>