背景
为了在项目内方便使用下载文件功能,封装下载文件指令。使用时只需要:
<div v-down="`下载地址`">下载</div>
指令源码
存放到src/directives/down.ts
import { Directive } from 'vue';
const downFileByUrl = async (url: string) => {
const link: HTMLElement = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("target", "_blank");
link.setAttribute("download", "");
link.click();
if (document.body.contains(link)) {
document.body.removeChild(link);
}
}
export const downFile: Directive = {
beforeMount(el, binding) {
const handler = () => {
const { value } = binding;
downFileByUrl(value);
};
el.__downFileHandler__ = handler;
el.addEventListener('click', handler);
},
unmounted(el) {
const handler = el.__downFileHandler__;
if (handler) {
el.removeEventListener('click', handler);
delete el.__downFileHandler__;
}
},
};
// 这个导出名称在自定义渲染函数时候结合withDirectives使用
export const vDown: Directive = downFile;
main.ts全局注册
import { createApp } from "vue";
import { downFile } from "@/directives/down";
const app = createApp(App);
app.directive("down", downFile);
app.mount("#app");
在sfc模板使用
<template>
<div v-down="`下载的url地址`">下载</div>
</template>
在编写渲染函数的场景结合h和withDirectives使用
render = () =>{
return withDirectives(
h('div',"下载"),
[[vDown, '下载的url地址']]
);
}