首页 > 解决方案 > 使用Vue js上传图片时如何显示图片预览?

问题描述

当用户上传图像时,我试图显示预览图像。出于某种原因,当我使用<input>带有常规 Bootstrap 类的时,我的代码可以工作form-control,但是当我使用 Bootstrap-Vue 时,<b-form-file>我得到一个错误:Error in render: "TypeError: Cannot read property 'name' of undefined"

数据:

data() {
            return {
                options: [
                    { text: "Full Time", value: "Full Time" },
                    { text: "Part Time", value: "Part Time" },
                ],
                profileData: {
                    photo: '',
                    employment_type: "Full Time",
                    date_of_birth: "",
                    experience: "",
                    skills: "",
                },

            };
        },

我的方法:

methods: {
            attachImage() {
                this.profileData.photo = this.$refs.profilePhoto.files[0];
                let reader = new FileReader();
                reader.addEventListener('load', function() {
                    this.$refs.profilePhotoDisplay.src = reader.result;
                }.bind(this), false);

                reader.readAsDataURL(this.profileData.photo);
            },
        }

引导代码,此代码有效:

<div role="group" class="form-group">
                        <label for="photo" class="d-block">Upload Profile Photo (optional)</label>
                        <div v-if="profileData.photo.name">
                            <img src="" ref="profilePhotoDisplay" class="w-100px" />
                        </div>
                            <input
                                id="photo"
                                v-on:change="attachImage"
                                ref="profilePhoto"
                                type="file"
                                class="form-control"
                            >
                    </div>

Bootstrap-Vue 代码,这给了我错误:

<div v-if="profileData.photo.name">
                        <img src="" ref="profilePhotoDisplay" width="140" />
                    </div>
                    <b-form-group label="Upload Profile Photo (optional)" label-for="image">
                        <b-form-file
                            id="photo"
                            v-on:change="attachImage"
                            ref="profilePhoto"
                            type="file"
                        ></b-form-file>
                    </b-form-group>

标签: laravelformsvue.jssingle-page-application

解决方案


推荐阅读