在main.js里加指令
//创建自定义指令 v-down
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 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() }) }) } })
在页面中使用,直接使用v-down就能实现下载功能
<div v-down="downLoadImage" > <img :src="downLoadImage" alt="会议签到二维码" width="300" height="300"> <span>点击下载</span> </div>
<script> export default { data(){ return{ downLoadImage: require('../assets/logo.png') } } } </script>
转自:https://www.jianshu.com/p/6ca0f2cd53c6