Update the state within a different function in Vue.js

Just starting out with Vue.js and I'm trying to figure out how to update the component's state from a function in another file. I have a basic form with only an input file element.

Once the user selects a file, the onChange handler will be triggered, but I'm unsure of how to update the state within other functions.

Here is the code snippet:

utils.js:

export const handleUpload = function(event, state) {
    console.log('Selected file: ', event.target.files[0]);
    // Need to update the selected state here.
};

Component:

<template>
  <div>
    <input
      type="file"
      accept="image/*"
      name="photo"
      @change="onFileSelection($event)"
    />
  </div>
</template>

<script>
import { handleUpload } from './utils';

export default {
  name: 'Index',
  date() {
    return {
      selected: null
    };
  },
  methods: {
    onFileSelection: handleUpload
  }
};
</script>

Answer №1

There are numerous methods to accomplish this task.

Keep handleUpload versatile and have it simply return data

One approach is to have handleUpload return a value that can be utilized by your VueJS component for further processing. By keeping handleUpload generic, you ensure that it does not contain any component-specific logic, as modifying state is specific to individual components.

export const handleUpload = function(event) {
    console.log('Selected file: ', event.target.files[0]);
    
    return event.target.files[0];
};

Then in your VueJS component:

data() {
    return {
        selected: null
    };
},
methods: {
    onFileSelection: function(event) {
        const file = handleUpload(event);
        
        // You can then update the component state here, for example:
        this.selected = file;
    }
}

Passing component reference to function (not recommended)

Although feasible, I personally do not recommend this approach as it adds a level of specificity to handleUpload, requiring knowledge of which specific component's data needs to be modified – which could vary between different components.

export const handleUpload = function(event, component) {
    console.log('Selected file: ', event.target.files[0]);
    
    component.selected = event.target.files[0];'
};

Then in your VueJS component:

data() {
    return {
        selected: null
    };
},
methods: {
    onFileSelection: function(event) {
        handleUpload(event, this);
    }
}

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

React-Native introduces a new container powered by VirtualizedList

Upon updating to react-native 0.61, a plethora of warnings have started appearing: There are VirtualizedLists nested inside plain ScrollViews with the same orientation - it's recommended to avoid this and use another VirtualizedList-backed container ...

Getting dynamic props from a clicked element in React involves accessing the target element's properties and

I am currently working with a React "tree" menu component that has main links with submenus generated dynamically through a JSON GET call. Upon inspecting the tree in the React Inspector, I noticed that each element has multiple props associated with it. H ...

Incorporating database coordinates into Marker React Leaflet: A Step-by-Step Guide

When I retrieve coordinates from the database, they are structured as "lat" and "lon" fields. In my mapping application, I have multiple markers to display. How can I combine these two fields to pass coordinates (coord.lat and coord.lon) to the Marker comp ...

Creating Awesome Icons in Kendo Grid with Code In this tutorial, we will learn how to programm

Looking to have a Kendo grid display a green fas-fa-clock icon if isActive is true, and a grey far-fa-clock icon if false. Clicking on the icon should toggle between true and false. Currently, the grid just shows the word true or false in the column. Cod ...

Why is my code executing twice rather than just once?

` import './App.css'; import ArrayState from './components/ArrayState'; import FetchApi from './components/FetchAPI/FetchApi'; import Login from './components/Login'; import Useeffect2 from './components/Use ...

Resource loading unsuccessful: server encountered a status of 500 (Internal Server Error)

I'm struggling to figure out why I keep getting an Internal Server Error when trying to call a web service in my HTML page using JavaScript and Ajax. Here is the error message: Failed to load resource: the server responded with a status of 500 (Int ...

What is the best way to delete a particular CSS class using jquery?

My task is to remove the "btn" class from items that have an additional argument in their class name, such as: <input type="button" class="btn btn-mini btn-success email-user" id="emailid5" value="Email Tester"> I specifically need to only remove t ...

Tips for locating an element beyond the page source with Puppeteer

My goal is to extract specific information from a webpage by utilizing this code snippet to target an element and retrieve certain values within it: const puppeteer = require('puppeteer'); function run (numberOfPages) { return new Promise(a ...

Steps for triggering a click event on a div with a button role within a class containing multiple elements

Can anyone help me figure out how to auto-click every button in Instagram's "hide story from" settings using console? I tried the following code: for (let i = 0; i < 300; i++) { document.getElementsByClassName('wbloks_1')[i] ...

VueJS does not support loading Jquery

When setting up my project with Bootstrap, I encountered an issue where even though I imported the jquery.min file before Bootstrap in my main.js file using require(), Bootstrap still threw an error saying that it requires jQuery. In my main.js file, I ha ...

What is the best way to customize the spacing of grid lines in chartist.js?

I am struggling with chartist.js. I want to increase the spacing between y-axis gridlines by 40px. (Currently set at 36px) I have tried looking for examples, but haven't found any. .ct-grids line { stroke: #fff; opacity: .05; stroke-dasharray: ...

Error: Module 'config' not found by Jest

I have encountered an issue while using Jest to test my api calls file. When running a simple test, I received an error Cannot find module 'config' from 'api.service.js'. This error is related to the import statement at the top of my ap ...

HTML5 Slideshow with Smooth Image Transitions

So, I have created an HTML5 image slideshow and it's working perfectly on my localhost. However, I am puzzled as to why there is no transition effect within the slideshow. I was expecting something like fading out the first picture and then having the ...

I'm having trouble getting onClick to function properly in CodeIgniter

While attempting to utilize onClick in the PHP page as shown below: <a href="javascript:void(0);" onClick="deleteCourse('<?php echo $row->courseId;?>');" class="delete">Delete</a> And in the JavaScript page, the function is ...

"Strategically placing elements on an HTML grid

My current project involves creating a grid layout in HTML using CSS. The goal is to use this layout for various elements such as images, text, and links. What I envision is a visually appealing grid where each object fits together seamlessly with no gaps ...

Having trouble correctly parsing XML data using JavaScript

My input field contains the following XML code: <?xml version="1.0" encoding="utf-8"?> <players timestamp="1536505850"> <player id="0518" name="Eagles, Philadelphia" position="Def" team="PHI" /> <player id="10271" name="Jones, Jul ...

What is the best method for enabling HTML tags when using the TinyMCE paste plugin?

After spending countless hours searching for a solution, I am still puzzled by this problem. My ultimate goal is to have two modes in my powerful TinyMCE editor: Allowing the pasting of HTML or Word/OpenOffice text with all styles and formatting attribu ...

Discover how to fetch data within Vue component using data access object in Vue 3

I am in the process of utilizing a data access object (dao) named Todos.js to fetch necessary data for a Vue3 component called List.vue. Below, you will find snippets from my code as an example. Upon initializing the application, the data is successfully ...

What is the best way to manage various versions of JS libraries across different branches?

As a novice developer, I dabble in creating applications for personal use. My go-to tools are the Quasar framework for the front end and Python for the back end. I maintain a git repository where the master branch houses my "production code," but now I am ...

Vue: updating the :root CSS variable for a child component leads to an error - TypeError: Unable to access properties of undefined (reading 'style')

Fiddle: https://codesandbox.io/s/hardcore-mestorf-w1lsob?file=/src/App.vue In my project, I have created two simple files that are responsible for displaying a circle on the screen: https://i.stack.imgur.com/0ddI3.png The goal is to modify the circular ...