首页 > 解决方案 > VueJs 在数组中渲染图像对象

问题描述

我想在渲染之前将图像对象转换为 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)
            })
        },

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

在此处输入图像描述

标签: javascriptvue.js

解决方案


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

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


推荐阅读