vue-cli实现下载文件而不是打开文件
vue-cli实现下载文件而不是打开文件
写一个vue指令,原理就是使用blob实现下载
Vue.directive('down', {
inserted: (el, binding) => {
el.style.cssText = 'cursor: pointer;color:write;'
el.addEventListener('click', () => {
// console.log(binding.value)
let link = document.createElement('a')
let image = document.createElement('image')
let url = binding.value
let downloadName = url.slice(url.lastIndexOf("/") + 1)
// console.log(downloadName);
// 这里是将url转成blob地址,
image.setAttribute("crossOrigin", "anonymous") // 这句可以解决跨域问题
fetch(url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
link.href = URL.createObjectURL(blob)
// console.log(link.href)
link.download = downloadName
document.body.appendChild(link)
link.click()
})
})
}
})
使用
<span v-down="item.path">下载</span>
结果