导出(vue3)

一 新打开一个页面导出 

   window.open(
     "https://。。。/collCusAide/page/export?authorization=ba10a639-bd05-47b2-90d9-7b2b75633925",
     "_blank"
   )

二、当前页面导出

common.ts中声明导出方法

import axios from "axios"
import dayjs from "dayjs"
/**
 * 通用文件下载方法
 * @param {string} url - 请求地址
 * @param {Object} params - 请求参数
 * @param {string} method - 请求方法 (默认: POST)
 */
export async function downloadFile({
  url,
  params = {},
  method = "POST",
  headers = {},
  name = "集客助手明细" + dayjs().format("YYYYMMDD")
}) {
  try {
    // 发起请求,设置 responseType 为 'blob'
    const response = await axios({
      url,
      method,
      data: method === "POST" ? params : undefined, // 仅 POST 时传递请求体
      params: method === "GET" ? params : undefined, // 仅 GET 时传递查询参数
      responseType: "blob",
      headers: {
        ...headers, // 合并传入的 headers
        authorization: localStorage.getItem("accessToken") // 添加 auth 参数
      }
    })
    // 创建 Blob 对象
    const blob = new Blob([response.data], {
      type: response.headers["content-type"] || "application/octet-stream"
    })

    // 从响应头中获取文件名
    const disposition = response.headers["content-disposition"]
    console.log(disposition, "disposition")
    const filename = disposition
      ? decodeURIComponent(disposition.split("filename=")[1]?.replace(/['"]/g, ""))
      : name + ".xlsx" // 默认文件名
    // 创建下载链接并触发下载
    const urlObject = window.URL.createObjectURL(blob)
    const a = document.createElement("a")
    a.href = urlObject
    a.download = filename
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)

    // 释放 Blob URL
    window.URL.revokeObjectURL(urlObject)
  } catch (error) {
    console.error("文件下载失败:", error)
    throw error // 抛出错误,便于外部处理
  }
}

2 使用 

 <el-button :loading="isLoading" class="importButton" @click="exportPage">导出</el-button>


import { downloadFile } from "@/utils/common"

/** 导出 */
const isLoading = ref<any>(false)
const exportPage = async () => {
  isLoading.value = true
  try {
    let params: any = toRaw(queryForm.value)
    delete params.pageIndex
    delete params.pageSize
    if (contactIds.value?.length > 0) {
      params.contactIds = contactIds.value
    }
    const baseUrl = /^https?:\/\/pre-/g.test(window.origin)
      ? "https://pre-。。。。/crm-web"
      : import.meta.env.VITE_API_BASE_PATH
    await downloadFile({
      url: baseUrl + "/collCusAide/page/export",
      params: params,
      method: "POST",
      headers: {}
    })
    // 更新列表
    delete queryForm.value.contactIds
    getJiKeList()
    jeKeTable.value?.clearSelection()
  } catch (err) {
  } finally {
    isLoading.value = false
  }
}

注意: 导出方法不加await ,   el-button的loading图案不会出来  : 因为异步并没有等着接口执行就已经走完了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值