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

Despite providing the correct token with Bearer, Vue 3 is still experiencing authorization issues

I am working on a project that involves Vue 3 with a Node Express back-end server and Firebase integration. On the backend server, I have implemented the following middleware: const getAuthToken = (req, _, next) => { if ( req.headers.authori ...

Creating unit tests without relying on a testing framework: A guide

My goal is to unit test a simple function using pure JavaScript: NS.isType = function (type, obj) { if (obj.constructor && obj.constructor.name) { return obj.constructor.name === type; } return toString.call(obj) === '[obj ...

What is the functionality behind app.listen() and app.get() in Hapi.js, Restify, and Koa?

Using the http node module, which consists of only native modules, how can I create a custom version of app.listen() and app.get() by utilizing the http module with a constructor? var app = function(opts) { this.token= opts.token } app.prototype ...

What is the best way to position a static element next to a Vue draggable list?

I'm currently working on implementing a feature to display a list of draggable elements using vue-draggable. These elements are occasionally separated by a fixed element at specified position(s). My approach so far has involved creating a separate el ...

Send all links that have the # symbol in them to a different location

Since switching the Vue router mode from hash to history, it seems that the old links are not correctly redirecting users to the new URL. It appears that some users are still trying to access the site through the old link. const router = new Router({ m ...

Create an Array with a dynamic name derived from the values of other variables

In my JavaScript project, I am facing a challenge in naming arrays based on dynamic data such as room numbers and user IDs. As the rooms and users are constantly changing, I need to create multiple arrays accordingly. Although this code is incorrect, it s ...

AngularJS: Index not refreshing after deletion of array item(s) using their indexes

I am attempting to eliminate a specific item from an array variable within AngularJS's scope by using the item's index. If you believe this question is a duplicate, please check out the footnote links for related questions that were not exactly ...

Issue with jQuery's outerHeight() function persisting despite attempting to fix it with jQuery(window).load()

Once the content is loaded using AJAX, I need to retrieve the outerHeight of the loaded elements. Ajaxload file: $('#workshop').submit(function(event){ $.ajax({ url: URL, type: 'POST', data: $(' ...

In order to enhance user experience, I would like the tabs of the dropdown in the below example to be activated by

function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } ...

Creating header menus with section labels in Windows 8 Metro can be easily accomplished by utilizing Javascript

Is there a way to create a navigation menu in Windows 8 Metro JavaScript that includes header menus and section labels, similar to the example shown below? ...

I desire to perform a specific task when there is a modification in the path using react router framework

Though I am mindful of it. props.history.listen((location, action) => { console.log("when route changes",location); }) However, I need to implement it in a slightly different way. For instance, let's cons ...

Adding HTML elements to a Vue Tooltip

Does anyone know how to implement a tooltip in Vue for a table cell that has more than 22 characters in its content? I was looking into using the v-tooltip library (https://www.npmjs.com/package/v-tooltip) Setting the tooltip's content with a simple ...

Using Angular's Jasmine SpyOn function to handle errors in $resource calls

I need to write unit tests for an AngularJS service that utilizes $resource. I want to keep it isolated by using Jasmine's spyOn to spy on the query() method of $resource. In my controller, I prefer to use the shorter form of query() where you pass su ...

The Laravel router-link function seems to only work on the initial attempt

I am facing an issue while trying to fetch results from the database in News.vue and display them in Topnews.vue. I have successfully fetched two links. Clicking on link1 displays the Topnews.vue template with all functionalities working properly. However, ...

Is it possible to use jQuery validate for remote parsing with two fields in a single call

Currently, I am facing an issue while trying to parse two values using jQuery's validate plugin to compare with an SQL database. The DateReceived value is successfully parsed, but the CentreID value always appears as null. Below is the code snippet I ...

The issue of Access-Control-Allow-Origin not functioning properly when using Ajax for a POST request

I am encountering an issue with the header "Access-control-allow-origin" when making a request using the following code: <script type='text/javascript'> function save() { $.ajax( { type: 'POST', ur ...

Importing an image from the public folder in a nested directory with Next.js

My images are stored in the public directory and all of my code is located in the src folder. Usually, when I try to import an image from src/page/page.js like: /image/logo/logo-dark.png, it works. But when I am importing images from the src/component/cor ...

Tips for uploading a jpg image to the server using react-camera

My objective is to transfer an image captured from a webcam to a Lambda function, which will then upload it to AWS S3. The Lambda function appears to work during testing, but I'm struggling to determine the exact data that needs to be passed from the ...

How does the Express server collaborate with Webpack middlewares to facilitate live reloading?

As I delve into node, express, and webpack, I find myself grappling with the concept of middleware. Upon examining the code snippet below, my current understanding is that once the web server is up and running and I navigate to http://localhost:7770/, the ...

Tips for activating autocomplete / IntelliSence for sass within vue documents on VS Code platform?

Despite using lang="sass" in my .vue files within VS Code, I am experiencing issues with the autocomplete feature for CSS properties. (Vetur is already installed on my system) Is there anyone who can provide a solution or suggest settings that need to be ...