Vue 中下载文本内容为指定格式文件

Vue 中下载文本内容为指定格式文件,代码如下,直接复制即可

<el-button style="margin-bottom: 15px" type="primary" size="small" icon="el-icon-download" @click="saveCode">下载</el-button>
// 下载提示
    saveCode() {
    
    
      this.$prompt('请输入文件名', '下载为txt文件', {
    
    
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^(.)+$/,
        inputErrorMessage: '文件名不能为空'
      }).then(({
     
      value }) => {
    
    
        this.$message({
    
    
          type: 'success',
          message: '下载成功'
        });
        // this.fileName data 中定义
        this.fileName = value;
        this.downloadCode();
      }).catch(() => {
    
    
        this.$message({
    
    
          type: 'info',
          message: '取消输入'
        });
      });
    },
    // 下载
    downloadCode() {
    
    
      //定义文件内容,类型必须为Blob 否则createObjectURL会报错,this.code 为文本内容
      let content = new Blob([this.code])
      //生成url对象
      let urlObject = window.URL || window.webkitURL || window
      let url = urlObject.createObjectURL(content)
      //生成<a></a>DOM元素
      let el = document.createElement('a')
      //链接赋值
      el.href = url
      el.download = this.fileName + '.txt'
      //必须点击否则不会下载
      el.click()
      //移除链接释放资源
      urlObject.revokeObjectURL(url)
      // this.fileName 重置为空
      this.fileName = ''
    },

猜你喜欢

转载自blog.csdn.net/weixin_44640323/article/details/120133759
今日推荐