- 技术栈:vue2
- 下面以若依框架为例
-
在 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(); }); }); }, }; -
在 directive/index.js 引入并注册
import down from "./down"; const install = function (Vue) { Vue.directive("down", down); }; export default install; -
main.js 中引入并使用
import directive from "./directive"; Vue.use(directive); -
页面中使用 自定义下载命令
<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>