自用 多文件上传图片显示

<style>
img {
    width: 50px;
    height: auto;
}
</style>

<template>
    <div id="app">
        <div id="nav">
        </div>
        <div>
            <input
                type="file"
                @change="changeFile"
                ref="changeFile"
                multiple="multiple"
            />
        </div>
        <div v-for="(item,index) in imgList" :key="item.id">
            <img:src="item.file.src" @click="deleteImg(index)"/>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            imgList: []
        };
    },

    methods: {
        changeFile() {
            let that = this;
            for (var i = 0; i < this.$refs.changeFile.files.length; i++) {
                if (
                    this.$refs.changeFile.files[i].type.slice(0, 5) === "image"
                ) {
                    let file = this.$refs.changeFile.files[i];
                    let reader = new FileReader();
                    // 调用reader.readAsDataURL()方法,把图片转成base64
                    reader.readAsDataURL(file);
                    // 监听reader对象的onload事件,当图片加载完成时,把base64编码賦值给预览图片
                    reader.onload = function() {
                        file.src = this.result;
                        // 再把file对象添加到img数组
                        that.imgList.push({
                            file
                        });
                        that.$refs.changeFile.value = "";
                    };
                }
            }
        },
        deleteImg(index) {
            this.imgList.splice(index, 1);
        }
    },
    mounted() {},
    watch: {
        imgList(a) {
            console.log(a);
        }
    }
};
</script>

  

猜你喜欢

转载自www.cnblogs.com/mubiao/p/10215803.html