Young L.
Young L.

Reputation: 1042

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

Hi i am new in vue js and i would like to ask you how to solvethis problem...

Basically i have my component where is hidden input for files. After i clicked button browser show me window for importing files from pc... AFTER i choose file i would like to take that file... check if is taht file image and show that image in my img tag...

My problem is taht i really don't know how to make code wait until i choose my file. Now if i for example console.log something it is no waiting for my upload.

<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>

Upvotes: 0

Views: 793

Answers (1)

coyotte508
coyotte508

Reputation: 9725

You can add a callback to the input to listen for file changes.

First edit the html:

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

Then you can handle what happens with the files selected in your component:

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

Upvotes: 1

Related Questions