VueJs在数组内部渲染图像对象

时间:2020-02-12 12:54:48

标签: javascript vue.js

我想在渲染之前将图像对象转换为base64数据url。图像对象位于数组中,我首先将其存储,如下所示

        handleFileChange(e, index) {

            let file = e.target.files[0]
            console.log(file)
            let myFilesLength = this.form.files.length
            myFilesLength += 1
            if (myFilesLength == index) {

                this.form.files.push(file)
            } else {
                let html = '<div class="modal-cont"><h4>Please insert image in sequence.'+
                    '</h4><div class="alert__icon"><span></span></div></div>'
                Swal.fire({
                    customClass: {
                        popup: 'error-modal',
                    },
                    html: html,
                    showCloseButton: true,
                    allowOutsideClick: false,
                })
            }
            e.preventDefault()
        },

然后我在html中使用了这个数组来显示我存储的图像

<div class="tabs--custom__select">
            <div class="number__select-box" v-for="index in [0, 1 ,2 ,3 ,4 ,5 ,6 ,7]" :key="index">
                        <div class="number__select-inr">
                            <a href="javascript:void(0);" class="custom-images">
                                <h2 v-if="index < form.files.length">
                                    <img @click="addAnswer(form.files[index])" :src="convertBase64(form.files[index])">
                                </h2>
                                <h2 v-else>
                                    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
                                </h2>
                            </a>
                        </div>
                    </div>
</div>

正如您在img元素src属性上看到的那样,我调用了另一个函数将图像对象转换为base64数据url我在下面显示的函数代码

        convertBase64(file) {

            const dataUrl = new Promise ((resolve, reject) => {

                var reader = new FileReader()
                reader.readAsDataURL(file)
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
            })

            dataUrl.then(url => {
                return url
            }).catch(error => {
                console.log('error  '+ error)
            })
        },

但是当我测试我的代码时,它将呈现出空白图像

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用URL.createObjectURL(files[0])生成网址。

codepen-https://codepen.io/anon/pen/XGYoyr