It is not possible to alter data within the @change event handler in Vue.js

In this particular component, there is an input[type=file] element. Additionally, within this field, there is an uploadFile handler that invokes the validateMessage method in an attempt to modify the error message displayed. While it appears that after changing this.error, everything is correct, the error does not appear in the div.error and remains empty when inspecting with vueDevtool. View data in vueDevTools

data() {
  return {error: ''}
},
   
methods: {

 validateFile(file) {
   if (! file.type.includes('video/')) {
     this.error = 'wrong format';
     console.log(this.error); // wrong format
   }
 },
 
 uploadFile(e) {
   const file = e.target.files[0];
   this.validateFile(file);
 },
}
<input type="file" 
       id="im_video" 
       name="im_video" 
       @change="uploadFile"
       class="hidden">
           
<div class="error">
  {{ error }}
</div>

Answer №1

Check out this functional example.

new Vue({
  el:'#app',
  data() {
    return {
     error: ''
    }
  },

  methods: {

   validateFile(file) {
      console.log(file.type);
     if (! file.type.includes('video/')) {
       this.error = 'incorrect format';
       //console.log(this.error); // incorrect format
     }
   },

   uploadFile(e) {
     this.error = '';
     const file = e.target.files[0];
     this.validateFile(file);
   },
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <input type="file" 
         id="im_video" 
         name="im_video" 
         @change="uploadFile"
         class="hidden">

  <div class="error">
    {{ error }}
  </div>
</div>

If you are utilizing a component, this will assist in passing data from child to parent by setting error from the child component to the parent.

Vue.component('upload-file',{
  template:`<div><input type="file" 
         id="im_video" 
         name="im_video" 
         @change="uploadFile"
         class="hidden"></div>`,
  data() {
    return {
     error: ''
    }
  },

  methods: {
   validateFile(file) {
      //
     if (! file.type.includes('video/')) {
       vm.$emit('filerror', 'incorrect format');
     }
   },

   uploadFile(e) {
    vm.$emit('filerror', '');
     const file = e.target.files[0];
     this.validateFile(file);
   },
  }
});
const vm = new Vue({
  el:'#app',
  mounted(){
    this.$on('filerror', function (msg) {
      this.error = msg;
    })
  },
  data:{
    error:''
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <upload-file></upload-file>
  <div class="error">
    {{ error }}
  </div>
</div>

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

Utilize two functions to incorporate an array of strings into an object

Currently, I'm in the process of developing a NoteEditor using react. Within my popup, I have 2 text areas. However, I have encountered an issue when attempting to add my array of strings into an object. The variable containing the arrayOfStrings retu ...

Navigating Angular with relative paths: A guide to locating resources

Here is the structure of my app: index.html main.ts app |--main.component.html |--main.component.ts |--app.module.ts |--note.png ... etc I am trying to include the note.png file in main.component.html which is located in the same folder. I have att ...

Define the format for the output file name in TypeScript

I am trying to change the filename of a TypeScript generated js file. How can I accomplish this? For instance, I currently have MyCompany.ClassA.ts The default output filename is MyCompany.ClassA.js However, I would like the output filename to be MyComp ...

Issue arises when there are several inline <script> tags containing parameters which result in filtered JSON output

As a newcomer to JavaScript, I am faced with the challenge of creating a centralized glossary within a confined educational environment (LMS) that lacks a database or any other facilitating elements. My objective is to develop a script hosted on our applic ...

In React, what is the process for passing a callback argument from a child component to a parent component?

Currently, I am going through the React tutorial on https://reactjs.org/tutorial/tutorial.html and making good progress. However, there is one aspect that I find confusing. Here is the complete code (codepen: https://codepen.io/gaearon/pen/EmmOqJ?editors=0 ...

sending arguments from app.js to route.js

I have a file called app.js with the code below, and I also have an additional file named router.js that handles requests such as post, read, etc. This is the app.js file: var express = require('express'); module.exports = function () { ...

Sending a tailored query string through a form

Currently, when I submit a form, it directs me to the URL www.domain.com/search/?maxprice=10000000. However, I want it to redirect me to a custom URL such as www.domain.com/search/maxprice_10000000/ I came across some JavaScript code that was supposed to ...

How to delete rows from a table in bootstrap with JavaScript

My goal is to create a table that allows users to delete specific rows using JavaScript and bootstrap. I attempted the standard method, but it doesn't seem to be working: <form action="scrivi.php" method="POST"> <t ...

Develop a regular expression tailored for jQuery validation purposes

I'm working with jQuery validation in my web form and I need to validate a text field with specific criteria: 1. Must contain a number. 2. The letters 'a' or 'A', 'b' or 'B' are allowed after the number. 3. Th ...

Could someone please guide me on how to use JQuery to set a radio button as checked?

<input type="radio" name="sort" value="2" id="myradio"> Is there a way to set this as the selected option using JQUERY? ...

Passing parameters in HTML web applications

My web application is accessible through the link ...:8080/EPQ/. It consists of a single HTML file with the following code: <input type="hidden" name="id" id ="id" > I am looking to pass a value for the 'id' parameter through the URL ...: ...

Guide on showing the content of an uploaded file as an object in JavaScript using file reader

When using the file upload function to upload a json file and read its contents, I am encountering an issue where the result is in string format instead of object. How can I display it as an object? Here is my code: .html <div class="form-group"> ...

What is the best way to personalize the Window.Confirm() dialog in JavaScript?

var val= confirm("Are you sure to cancel?"); The code snippet above will display a popup with two choices - Ok and Cancel, with Ok being the default choice. Is there a way to make Cancel the default choice instead and switch the positions of the ...

What is the process for including echo HTML field in the WooCommerce order view?

I have successfully added HTML input fields within functions.php. However, these echoed fields are not displaying in WooCommerce orders after placing an order. I am looking for a way to include the values and labels of these fields in the orders view wit ...

The timer will automatically refresh when the page is refreshed

Currently, I am encountering an issue while working on a quiz application in PHP. The problem arises when users start the test and the timer is running correctly. However, when users move to the second question, the timer resets again. Below is the code sn ...

How can I efficiently create an editForm in Angular?

Within my database, there are numerous users, each with their own collection of recipes. Each recipe contains various properties and a list of ingredients. Take a look at the screenshot below: Recipe with all properties When a user goes to edit a recipe ...

Tips for modifying a request api through a select form in a REACT application

Apologies if this question seems a bit basic, but I need some help. I am working on creating a film catalog using The Movie Database API. I have successfully developed the home and search system, but now I am struggling to implement a way to filter the fi ...

Controller Function Utilizing Private Variable in AngularJS

After stumbling upon an Angularjs example online, I found myself perplexed. The code snippet in question is as follows: angular.module("testApp",[]).controller("testCtrl", function($scope){ var data = "Hello"; $scope.getData = function(){ ...

There are no @mousedown or @mouseup events available in Quasar's q-btn component

Is there a way to incorporate functionality on mouse-down/up in a q-btn element in Quasar 0.14.7, like starting a claxon on mouse down and stopping it on mouse up? It seems to only bind @click. Any suggestions on how to implement this kind of functionali ...

Matching dynamic routes with a slug and number in vue.js is a powerful feature that

Seeking assistance with creating a route pattern for eShop product slugs. The URLs in question are as follows: http://example.com/product/product-title-51 http://example.com/product/another-product-title-137 http://example.com/product/another-product-45-t ...