Exploring Vue.js: Pre-viewing an Image Before Updating it

Hey there! I have a custom component where I am trying to display an image. I want to show a preview of the image after selecting it, but before uploading it to the server. Can someone please help me with this? I attempted to use the v-on:change event on the img tag, but it doesn't seem to be working. My intention was to use the test() function to achieve the image preview.

<template>
    <div id="insert-component">
        <div id="insert-new" >
            <h2 class="text-md-left">New Category</h2>
            <div class="mt-2 text-left">
                <a href="#" id="img-button" class=" d-flex flex-wrap" v-on:click.stop="loadImage()">
                    <img src="/storage/images/no_image.png" alt="logo" v:on-change="test()">
                    <input type="file" class="d-none" id="load-category-image"  v-on:input="handleFileSelected">
                    <button class="btn btn-dark btn-block" >Add Image</button>
                </a>
                <small class="text-danger d-none error">File must be png, jpg, or jpeg</small>
            </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",
        props: [ 'updateTableData' ],
        data: function () {
            return {
                category_name: "",
                category_description: "",
                category_img:"/storage/images/no_image.png",
                file:null
            }
        },
        methods: {
            test(){
              alert("test");
            },
            loadImage(){
                document.getElementById('load-category-image').click();
            },
            handleFileSelected(event) {
                const acceptedImageTypes = ['image/jpg', 'image/jpeg', 'image/png'];
                let loadedFile = document.getElementById('load-category-image').files;
                if(acceptedImageTypes.includes(loadedFile[0]['type']))
                {
                    this.category_img="/storage/images/"+loadedFile.name;
                    this.file=loadedFile;
                }
                else{
                    let $errorsElements = document.getElementsByClassName('error');
                    for (let item of $errorsElements) {
                        item.classList.remove('d-none');
                    };
                    category_img="/storage/images/no_image.png";
                }
            },
        },
    }
</script>

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

How can we pass an optional boolean prop in Vue 3?

Currently, I am in the process of developing an application using Vue 3 and TypeScript 4.4, bundled with Vite 2. Within my project, there exists a file named LoginPage.vue containing the following code: <script lang="ts" setup> const props ...

Unleashing the Power of v-model in Vue.js: A Comprehensive Guide to Referencing Input

I am a beginner in vue.js and I am currently facing an issue with making a get request from a field that has a v-model="embed.url" after pasting a link. The paste event works fine, but I'm struggling to reference the input with v-model="embed.url" and ...

Utilizing parameters for data filtering in VueX getters

I'm really stuck on this issue. I've been trying to retrieve a blog post object using a getter based on its "slug". Despite all my attempts, every time I try to use the getter, I keep getting an error saying "state.posts.filter" is not a function ...

Error: Tried to modify a property that is read-only while using the useRef() hook in React Native with Typescript

https://i.sstatic.net/jhhAN.pngI'm facing an issue while attempting to utilize a useRef hook for a scrollview and pan gesture handler to share a common ref. Upon initializing the useRef() hook and passing it to both components, I encounter an error th ...

Ways to center align text in a div vertically

I'm working with 2 divs that are floating side by side. The left div contains a part number, which is only one line. The right div holds the product description, which can span multiple lines. I am looking for a way to vertically align the text in t ...

While attempting to deploy my project on Vercel by pulling in my code from GitHub, I ran into this error

As a self-taught Front End developer diving into building and hosting my first web page using React, I've encountered this warning. Any suggestions on how to resolve it? Cloning gitohub.com/Passion94/React-Apps (Branch: main, Commit: da89a2a) Cloning ...

It seems that the maximum call stack size has been exceeded, resulting in a

Within this dropdown, I have incorporated a checkbox containing values in the form of an object. (refer to attached image) Every time I make a selection from the dropdown, there is a watch function that updates this new value, which is essentially an arra ...

Default Data Configuration for Mongoose

Exploring the realm of node.js and the MEAN stack, I am venturing into the creation of an application. Within this application, there exists a need for default data in the database. My goal is to ensure that this data is populated automatically upon the ap ...

Having difficulty locating audio files within a Next.js project

I am facing challenges when trying to import my audio files into a redux slice. Currently, I am attempting to retrieve my audio files from the app > public > audio directory. I have made efforts to access my audio files through 2 different director ...

creating a JSON object in PHP that can be easily parsed by JavaScript

In my project, I have an extensive list of items, each item further divided into four sub-items. While it's convenient for me to organize this data in nested arrays using PHP, I encounter issues when trying to transfer them as a JSON object to the cli ...

What is the best way to extract data from two dropdown menus and send it to separate URLs?

I need assistance with extracting the selected year value from the first dropdown. I would like to append this value to the URL of the header page and also to the options in the second dropdown. This way, when I select a PHP page from the second dropdown ...

What causes a syntax error when trying to create an array of objects within a map using colons?

In my Google Apps Script, I created a function to retrieve the date and subject of emails with a specific label in Gmail. However, when attempting to store each result as an object, I encountered a SyntaxError: unexpected token ':' issue. Althoug ...

Encountered an issue: Error message stating that a Handshake cannot be enqueued as another Handshake has already been enqueued

I am currently working on setting up a node.js server to handle POST requests that involve inserting data into two separate MySQL tables. Below is the code snippet for my node.js server: let mysql = require("mysql"); const http = require('h ...

Generating an HTML table with JSON data in JavaScript

I'm still struggling with JavaScript as a beginner, so please bear with me and provide guidance step by step. Also, try to avoid overwhelming the comments with links as it confuses me. This is an attempt to bypass the CORS issue. <!D ...

My API is feeding data to the Material UI CardMedia image

Has anyone encountered a similar error while using the CardMedia API provided by Material-UI? I am currently utilizing the Card & CardMedia components from material-ui to display data fetched from an api. However, I am facing difficulty in displaying ...

What is the best way to extend an inline-block element to cover the entire text line?

Let's talk about the scenario: https://i.stack.imgur.com/we05U.png In the image, there is a container (displayed as a div) with only one child - a span element. The goal is to introduce a second child that occupies the entire red space depicted in t ...

Discovering ways to enhance time multiplication with JavaScript

My MVC model provides me with a timespan like this: timeTaken = "00:01:00"; Along with a multiplier value of multiply = "3"; The end result should be 00:03:00 What would be the most efficient way to calculate this time? I'm not well-versed in ...

What is preventing Protractor from detecting Angular on a site that has been automatically initialized with Angular?

Whenever I try to utilize browser.get() in my code, I encounter the following error: Error: Angular could not be found on the page http://localhost:5000/#/login debug=timing&saveLogs=true&displayAll=true : angular never provided resumeBootstrap A ...

What is the best way to incorporate additional list items into a field input?

I have been working on developing a simple to-do app and I am encountering an issue. After the user clicks enter in the input box, nothing happens as expected. Despite trying various methods, the problem persists. Below is the recent code that I have been ...

Extremely sluggish pagination in JQGrid following the implementation of a filter through the filter toolbar

I've encountered a problem while using jqGrid with LOAD ONCE and client-side paging. The addition of a filter toolbar has significantly slowed down the paging process after applying any kind of filter. $(gridElement).jqGrid({ postData: post, ...