vue复制base64图片到剪贴板
时间: 2023-12-05 17:39:45 浏览: 201
可以使用clipboard.js库来实现vue复制base64图片到剪贴板的功能。具体步骤如下:
1.安装clipboard.js库
```shell
npm install clipboard --save
```
2.在需要使用的组件中引入clipboard.js
```javascript
import Clipboard from 'clipboard';
```
3.在mounted钩子函数中初始化clipboard.js
```javascript
mounted() {
const clipboard = new Clipboard('.copy-btn');
clipboard.on('success', e => {
console.log('复制成功');
e.clearSelection();
});
clipboard.on('error', e => {
console.log('复制失败');
});
}
```
4.在template中添加复制按钮和图片
```html
<template>
<div>
<img :src="imgSrc" alt="">
<button class="copy-btn" data-clipboard-text="imgSrc">复制</button>
</div>
</template>
```
5.在methods中定义b64toBlob方法将base64编码转换为Blob对象
```javascript
methods: {
b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
return blob;
}
}
```
阅读全文