Learn how to upload an image using Vue.js and then trigger a custom method

Greetings! I am a newcomer to Vue.js and I have encountered a problem that I need help with. In my component, there is a hidden input for files. When I click a button, the browser displays a window for importing files from my PC. Once I choose a file, I want to retrieve that file, check if it is an image, and display that image in an img tag.

My issue is that I am unsure how to make the code wait until I select my file. Currently, if I try to console.log something, it does not wait for my upload.

<template>
    <div id="insert-component">
        <div id="insert-new" >
            <h2 class="text-md-left">New Category</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)">Add Image</button>
                </a>
            </div>
            <div class="form-group mt-2 text-left">
                <label for="name">Category Name:</label>
                <input type="text" name="name" class="form-control">
                <label for="description" class="mt-2">Category Description:</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)">Add Category</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>

Answer №1

To detect changes in a file, you can attach a callback function to the input element.

Start by updating the HTML code:

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

Next, define how to handle the selected files in your component:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to transfer the data from one JavaScript object to a new, empty object?

My Angular site requires a JavaScript object (JSON retrieved from a database) to display widgets: [{'widget_id':'1','widget_name':'Blue Widget','widget_description':'A nice blue widget','wid ...

Using the TIMESTAMP data type in PostgreSQL and getting the most out of it

After saving a Luxon datetime value in a TIMESTAMP(3) type column in a postgres database, I encountered difficulty using it for various operations like converting time zones. Despite creating the object with the code snippet below: const { DateTime } = req ...

Verifying StartDate and EndDate using AngularJS and Bootstrap Datepicker

My HTML Coding <form name="myForm"> <div class="row"> <div class="col-md-2"> <input data-ng-model="Data.StartDate" type="text" id="startDate" name="startDate" class="form-control" data-da ...

Struggling to access a remote URL through jQuery's getJSON function with jsonp, but encountering difficulties

Currently, I am attempting to utilize the NPPES API. All I need to do is send it a link like this and retrieve the results using jQuery. After my research, it seems that because it is cross-domain, I should use jsonp. However, I am facing difficulties m ...

Hide the search results if the user leaves the input field blank

I am trying to implement Live Search JSON Data Using Ajax jQuery, and I want to be able to search through multiple JSON files. When the page initially loads with an empty input field, no results are displayed. However, if you type and then delete text in ...

As the user types, the DD/MM/YYYY format will automatically be recognized in the

In my React component, I have an input box meant for entering a date of birth. The requirement is to automatically insert a / after each relevant section, like 30/03/2017 I am looking for something similar to this concept, but for date of birth instead of ...

Strategies for transferring retrieved data to the getServerSideProps function

I am currently utilizing the Context API to retrieve data and then pass that data to the getServerSideProps function, but encountering the following error: The React Hook "useContext" is being called in a function "getServerSideProps" that is neither a Re ...

Struggling to transfer information from JavaScript to Python Flask?

I am currently working on a basic configuration where I need to send a string to my Flask application through Ajax, but unfortunately, I am encountering Error code 400: Bad request. Here is the JavaScript code snippet: headers = { 'Content-type&a ...

Import a JavaScript file with beneficial test functions for selenium testing

Utilizing the runScript command in selenium has proven to be incredibly helpful for me. I've been using it to calculate values within a table and then store the result like so: <tr> <td>runScript</td> <td>var cumulativ ...

The transformation in the resulting array is evident when a nested array is altered after being concatenated using Array.concat

MDN explains concat as follows: The concat() function is utilized to combine two or more arrays without altering the original arrays. Instead, it produces a new array. Let's examine the code snippet below: Example 1 const array1 = [['a& ...

How can I make an image tag perfectly fit a CSS grid cell without using object-fit?

In this Vue component, the parent element displays 8 instances of these components in a 2x4 grid layout. The issue arises when the image within each component is larger than its container, causing it to not shrink to fit while maintaining the aspect ratio ...

Obtain the Encoded Data

Unfortunately, I do not have control over domain.com. However, I am able to provide a redirect URL parameter like the one shown below: www.domain.com?retUrl=www.example.com%3Fparameter%3Dvalue Following the provision of retURL (www.example.com?parameter= ...

Find the most recent date in a file and display the line associated with it

I am working with a document named Application.txt that consists of multiple columns and rows as shown below: ApplNo DocsURL DocDate 4782 www…. 7/28/2003 4782 www…. 11/23/2008 4782 www…. 3/24/2012 5010 www…. 4/5/2003 5010 ww ...

Passing a service into a directive results in an undefined value

Can someone help me understand why a service I am injecting into a directive is returning undefined in certain instances? If you would like to take a look at the code, here is a plunker link: https://plnkr.co/edit/H2x2z8ZW083NndFhiBvF?p=preview var app = ...

Confirm the data in each field of a form individually

I am facing an issue with a form that contains 7 fields. When I submit the form to the "register.php" page, it processes each field one by one and outputs the result as a whole. However, I need to validate the data using ajax, collect the output one by one ...

Tips for verifying a list of objects within a request body with JOI

I'm in the process of validating the request body for an order placement. The request body contains an array of JSON objects that I need to validate, but I keep encountering the error message "productId" is required. Below is the structure of my requ ...

Is there a more efficient algorithm available to solve this problem in a quicker manner?

I'm currently working on iterating through the body tag and all of its nested children. I want to be able to access each child, even if they contain additional children within them. Can anyone offer a more efficient algorithm than the one I came up wi ...

JavaScript Hangman Game Malfunctioning

I am in the process of creating a basic hangman game to be played on a web browser. Whenever the user clicks a button, it triggers a function called pickWord(): <button onclick="pickWord()" id="restart">Choose A Word</button> This functi ...

Confirming if the value is an array using jQuery

Currently, I have a list of elements with various types associated with them. My goal is to identify specific text within these types and hide only those types that do not contain the desired text, leaving the rest unaffected. The structure looks like thi ...

Navigating through props outside a class component in React

I'm struggling to grasp how I can access props that are defined outside of a React class component. In the code snippet below, all props are clearly outlined except for this.props.checkboxArray, which is currently throwing an error "cannot read prope ...