文件下载之自定义指令

158 阅读1分钟

1.新建download.js文件

export default {
  inserted: (el, binding) => {
    el.style.cssText = "cursor: pointer;color:write;";
    el.addEventListener("click", () => {
      console.log(binding.value);
      let link = document.createElement("a");
      let url = binding.value;
      let urlFormat = url.split("/");
      // 这里是将url转成blob地址,
      fetch(url)
        .then((res) => res.blob())
        .then((blob) => {
          // 将链接地址字符内容转变成blob地址
          link.href = URL.createObjectURL(blob);
          console.log(link.href);
          link.download =
            urlFormat.length > 0 ? urlFormat[urlFormat.length - 1] : "";
          document.body.appendChild(link);
          link.click();
        });
    });
  },
};

2.全局注册


import download from "./download";

Vue.directive("download", download);