在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