首页 > 解决方案 > 如何使用户能够使用 vue 从剪贴板粘贴图像?

问题描述

在我的模板中,我有:

        <textarea @paste.prevent="fileChange" ref="canvas" /></textarea>

在我的脚本中,我有一个方法:


fileChange(event){

  console.log(event.clipboardData.items[0].kind) 

  ....

}

在我的控制台上,当触发 fileChange 事件(通过粘贴)时,我不断收到一个字符串。

标签: javascripthtmlvue.jspaste

解决方案


尝试这个

在我的组件中我使用了这个(listeningn paste 事件)

                    <b-form-textarea
                            @paste="pasteFunction"                                
                    ></b-form-textarea>            

在我的函数中得到了这个

pasteFunction(pasteEvent, callback){

if(pasteEvent.clipboardData == false){
    if(typeof(callback) == "function"){
        console.log('Undefined ')
        callback(undefined);
    }
};

var items = pasteEvent.clipboardData.items;

if(items == undefined){
    if(typeof(callback) == "function"){
        callback(undefined);
        console.log('Undefined 2')
    }
};
for (var i = 0; i < items.length; i++) {
    
    if (items[i].type.indexOf("image") == -1) continue;
    var blob = items[i].getAsFile();
    this.addImage(blob)
}
}

最后,我用另一种方法处理图像

       addImage(file){
            if (!file.type.match('image.*')) {
                return new Promise((reject) => {
                    const error = {
                        message: 'Solo puede arrastrar imágenes.',
                        response: {
                            status: 200
                        }
                    }
                    this.$obtenerError(error)
                    reject()
                    return;
                })
            }

            this.files.push(file);
            const img = new Image(),
                reader = new FileReader();

            reader.onload = (e) => this.images.push(e.target.result);
            const str = JSON.stringify(file);

            reader.readAsDataURL(file);
           }

在我的前面可以看到所有这样的图像

                    <div class="img-wrapper" v-for="(image, index) in dimg" :key="index">
                        <img style="max-width:230px; max-height: 230px;" thumbnail center rounded  class="max-image-upload" :src="image" :alt="`Image Uplaoder ${index}`">
                    </div>

推荐阅读