vue2+下载文件(静态文件)

<template>
  <div class="router-container">
    <!-- 下载 -->
    <el-button @click="downLoad">
      <i class="iconfont icon-down"></i>{{ $t('area.title2') }}</el-button
    >
  </div>
</template>
<script>
export default {
  mounted() {
    if (process.env.NODE_ENV !== 'development') {
      this.href = parent.window.location.origin + '/区域导入模板.xlsx'
    } else {
      this.href = parent.window.location.origin + '/区域导入模板.xlsx'
    }
  },
  methods: {
    // 下载模板
    downLoad() {
      let xhr = new XMLHttpRequest()
      //get后边是public文件夹下需要下载的模板的文件名
      xhr.open('get', `/区域管理模板.xlsx`, true)
      xhr.responseType = 'blob'
      xhr.onload = function () {
        if (this.status == 200) {
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(this.response)
          downloadElement.href = href
          //这个也是文件名
          downloadElement.download = '区域管理模板.xlsx'
          document.body.appendChild(downloadElement)
          downloadElement.click()
          document.body.removeChild(downloadElement)
          window.URL.revokeObjectURL(href)
        }
      }
      xhr.send()
    }
  }
}
</script>

Vue3、Vite 和 TypeScript 的组合通常用于构建高性能的现代Web应用。对于静态图片处理,你可以采用以下步骤: 1. **安装依赖**: - 使用`npm`或`yarn`安装`vue.config.js`文件,以便配置Vite支持TypeScript:`npm install @vitejs/plugin-vue@next typescript` - 如果需要处理图片,安装一个图片处理库,如`sharp`(Node.js的高性能图像处理库),但在客户端运行Vite时,可能不会直接引入,因为Vite默认会打包到浏览器。 2. **配置Vite**: - 在`.viteignore`文件中忽略`node_modules`,防止打包过多不必要的体积。 - 更新`vite.config.ts`,添加TypeScript支持,配置Vite插件: ```typescript import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; export default defineConfig({ plugins: [vue()], build: { target: 'esnext', tsconfig: './tsconfig.build.json', // 根据项目需求配置正确的TS编译配置 }, }); ``` 3. **图片资源管理**: - 将图片放入`public`目录下,Vite会自动处理静态资产。 - 对于动态生成的图片(例如需要根据某些条件调整大小或添加水印),可以使用JavaScript (ES6+) 动态创建Image对象,或者在服务器端渲染时使用像`sharp`这样的库处理图片后再返回给前端。 4. **使用TypeScript**: - 引入图片处理模块时,确保正确导入并处理类型安全: ```typescript import sharp from 'sharp'; // 假设sharp是全局可用的,若不在Node环境则需引入库 async function resizeImage(src: string): Promise<Buffer> { const resized = await sharp(src) .resize(300, 200) // 设置新尺寸 .toBuffer(); // 转换为Buffer对象 return resized; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值