【问题标题】:Vue.js how to upload image and AFTER THAT run custom methodVue.js如何上传图片并在运行自定义方法之后
【发布时间】:2020-03-17 21:44:19
【问题描述】:

您好,我是 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>

【问题讨论】:

    标签: javascript vue.js ecmascript-6


    【解决方案1】:

    您可以向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);
            }
        },
    

    【讨论】:

      猜你喜欢
      • 2019-06-07
      • 1970-01-01
      • 2017-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      相关资源
      最近更新 更多