繁体   English   中英

Vue.js 如何在更新前显示图像预览

[英]Vue.js how to show image preview before update

嗨,我有我正在加载图像的自定义组件。 我需要在选择图像后和将其上传到服务器之前显示该图像。 请问这个怎么做? 我尝试在 img 标签上使用 v-on:change 效果,但它不起作用。 我的计划是使用 test() 函数来进行图像预览。

<template>
    <div id="insert-component">
        <div id="insert-new" >
            <h2 class="text-md-left">New Category</h2>
            <div class="mt-2 text-left">
                <a href="#" id="img-button" class=" d-flex flex-wrap" v-on:click.stop="loadImage()">
                    <img src="/storage/images/no_image.png" alt="logo" v:on-change="test()">
                    <input type="file" class="d-none" id="load-category-image"  v-on:input="handleFileSelected">
                    <button class="btn btn-dark btn-block" >Pridať obrázok</button>
                </a>
                <small class="text-danger d-none error">Súbor musí byť png, jpg alebo jpeg</small>
            </div>
        </div>
        <button class="btn btn-success btn-block my-2" v-on:click="submit($event)">Pridať kategóriu</button>
    </div>
</template>
<script>
    export default {
        name: "InsertComponent",
        props: [ 'updateTableData' ],
        data: function () {
            return {
                category_name: "",
                category_description: "",
                category_img:"/storage/images/no_image.png",
                file:null
            }
        },
        methods: {
            test(){
              alert("test");
            },
            loadImage(){
                document.getElementById('load-category-image').click();
            },
            handleFileSelected(event) {
                const acceptedImageTypes = ['image/jpg', 'image/jpeg', 'image/png'];
                let loadedFile = document.getElementById('load-category-image').files;
                if(acceptedImageTypes.includes(loadedFile[0]['type']))
                {
                    this.category_img="/storage/images/"+loadedFile.name;
                    this.file=loadedFile;
                }
                else{
                    let $errorsElements = document.getElementsByClassName('error');
                    for (let item of $errorsElements) {
                        item.classList.remove('d-none');
                    };
                    category_img="/storage/images/no_image.png";
                }
            },
        },
    }
</script>

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

代码笔 - https://codepen.io/anon/pen/XGYoyr

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM