Vue2 - 前端下载网页文件保存到本地 - 自定义命令

124 阅读1分钟
  • 技术栈:vue2
  • 下面以若依框架为例
  1. 在 directive 文件夹下创建 down.js

     
     /**
      * 下载文件
      */
     export default {
       bind: (el, binding) => {
         el.addEventListener("click", () => {
           let link = document.createElement("a");
           let url = binding.value;
    
           // 这里是将url转成blob地址,
           fetch(url)
             .then((res) => res.blob())
             .then((blob) => {
               // 将链接地址字符内容转变成blob地址
               link.href = URL.createObjectURL(blob);
               console.log(link.href);
               link.download = ""; //为空使用下载名称
               document.body.appendChild(link);
               link.click();
             });
         });
       },
     };
    
     
    
  2. 在 directive/index.js 引入并注册

    
    import down from "./down";
    
    const install = function (Vue) {
      Vue.directive("down", down);
    };
    
    export default install;
    
    
  3. main.js 中引入并使用

    import directive from "./directive";
    
    Vue.use(directive);
    
  4. 页面中使用 自定义下载命令

                  <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                      <el-button size="mini" type="text" icon="el-icon-download" v-down="`${scope.row.attachment}`">
                        下载
                      </el-button>
                    </template>
                  </el-table-column>