繁体   English   中英

Vue.js 如何上传图片和之后运行自定义方法

[英]Vue.js how to upload image and AFTER THAT run custom method

嗨,我是 vue js 的新手,我想问你如何解决这个问题......

基本上我有我的组件,其中隐藏了文件的输入。 在我点击按钮浏览器向我显示从 PC 导入文件的窗口后...在我选择文件后,我想获取该文件...检查是否是 taht 文件图像并在我的 img 标签中显示该图像...

我的问题是我真的不知道如何让代码等到我选择我的文件。 现在,如果我例如 console.log 的东西,它不会等待我的上传。

<template>
    <div id="insert-component">
        <div id="insert-new" >
            <h2 class="text-md-left">Nová kategória</h2>
            <div class="mt-2">
                <a href="#" id="img-button" class=" d-flex flex-wrap">
                    <img src="/storage/images/no_image.png" alt="logo">
                    <input type="file" class="d-none" id="load-category-image">
                    <button class="btn btn-dark btn-block" v-on:click="loadImage($event)">Pridať obrázok</button>
                </a>
            </div>
            <div class="form-group mt-2 text-left">
                <label for="name">Názov kategórie:</label>
                <input type="text" name="name" class="form-control">
                <label for="description" class="mt-2">Popis kategórie:</label>
                <textarea name="description" class="form-control" rows="4">
                </textarea>
            </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",
        data: function () {
            return {
                state: 0
            }
        },
        methods: {
            loadImage($e){
                $e.preventDefault();
                document.getElementById('load-category-image').click();
                console.log("MY PROBLEM IS HERE, code normal continue");
            },
            test(){
                alert('HI');
            }
        },
    }
</script>

您可以向input添加回调以侦听文件更改。

首先编辑html:

<input type="file" class="d-none" id="load-category-image" v-on:change="handleFileSelected">

然后你可以处理在你的组件中选择的文件会发生什么:

    methods: {
        loadImage($e){
            //...
        },
        handleFileSelected(event) {
            const files = document.getElementById('load-category-image').files;
            console.log(files);
        }
    },

暂无
暂无

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

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