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

How can I pass the current value of an HTML.DropDownListFor to an ActionLink?

Is it feasible to transfer the current value of @Html.DropDownListFor to an action link? I am trying to send the template value to the Sample controller using the Create action. The code below is not functioning because @Model.SurveyTemplate does not retur ...

The jQuery countdown plugin is yielding some unexpected outcomes

Feeling a bit rushed for time, so I thought I'd ask here. The date is currently 2012-10-06 and I'm attempting to implement a jQuery plugin called "jquery.countdown.js". It seems pretty straightforward. Can anyone point out what I might be doing i ...

The mesmerizing world of Vue templates and transition groups

My previous simple list had transitions working perfectly, but now that I am using components and templates the transitions no longer work. Can anyone help me understand why? I want each item to animate individually, but it seems like all items are transi ...

Using PHP, JavaScript is unable to hide <div> elements

I'm encountering an issue where the div I want to show when an error occurs is not hiding and showing properly using JavaScript. Here is a snippet of my code: <script> function hideerror() { var catdiv = document.getElementById(error); ...

What is the NodeJs Event loop and how does it work with libuv and V8

NodeJs is made up of the V8 engine and the libuv library. The V8 engine has its own event loop with a call stack, event queue, and micro task queue to run our main code. The libuv also has an event loop with phases like times, callbacks, poll, check, and ...

The markers within a loop in react-native-maps are failing to render

Recently, I've been delving into the world of React Native app development for iOS. Specifically, I've been experimenting with the react-native-maps package. Here's the issue I'm facing: When I statically render a single MapView.Marker, ...

How do you send a variable in a GET request with React?

My challenge is to retrieve data from a table where the teacherId matches the teacherId of the user who logs in, but I am facing difficulties in passing this teacherId from the front-end to the back-end. Below is the backend code: app.get("/api/get&q ...

Embed a function within a string literal and pass it to another component

Is there a way to pass a function defined in actions to an element? Reducer case 'UPDATE_HEADER': return Object.assign({}, state, { headerChildren: state.headerChildren.concat([action.child]) }); Action.js export const deleteH ...

A handy tip for sending a response once a for each loop has finished executing

It is important that Response.json executes only after the foreach loop has completed its execution. var todoarr = (req.body.data) ? req.body.data : undefined todoarr.forEach(function(element) { if(element.done == true) { TodoS ...

The Angular route functions flawlessly in the development environment, but encounters issues when deployed to

I have a project built with Angular 2, During development on localhost, everything runs smoothly. However, once I build a production version using (npm run build: prod) and navigate to the route on the server, I encounter a 404 error indicating that the r ...

Search for text in multiple tables using jQuery and automatically trigger a button click event when the text is found

I am attempting to query certain tables and click a button within a cell of a specific table. Below is the code I am currently using: links[1].click(); iimPlayCode('WAIT SECONDS = 2') var compTabs = window.content.document.getElementById(' ...

What is the best way to customize the styles of Material UI V5 Date Pickers?

Attempting to customize Mui X-Date-Pickers V5 through theme creation. This particular component is based on multiple layers. Interested in modifying the borderColor property, but it's currently set on the fieldset element, so need to navigate from Mu ...

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 ...

How can one create custom JavaScript UI controls for a UWP application?

I am currently working on a UWP application and I am looking to incorporate JavaScript HTML5 based UI components. Is there a method to integrate this UI into a UWP application? My UI is completely developed using JavaScript, jQuery, CSS, and HTML5, and I w ...

Storing dataset characteristics in a JSON file utilizing Vue.js form response

I am currently working on creating a JSON file to store all the answers obtained from a Form. Some of the input fields have an additional dataset attribute (data-tag). When saving the Form, I aim to extract these 'tags' and include them in the JS ...

Utilizing asynchronous operations dependent on the status of a separate entity

Dealing with asynchronous operations in Vue has been a challenge for me. Coming from a C# background, I find the async-await pattern more intuitive than in JavaScript or TypeScript, especially when working with Vue. I have two components set up without us ...

Guide on changing the order of Vue sibling components when rendering a shared array within a parent component list

Currently facing a unique challenge and seeking input: Within the 'App', utilize 'TestListItem' for odd item indexes and 'TestListBetterItem' for even indexes. The same index must be used for both components. Initial attemp ...

What could be causing my ajax request to not be successfully compiled?

I seem to be experiencing an issue with this part of my code. Despite trying multiple methods, it still isn't functioning correctly. What steps can I take to resolve this problem? $.ajax({ url: "https://corona-api.com/countries/BR", ...

Tips for triggering a click event on a DOM element using Angular 2

How can I automatically load a component upon loading? <app-main id="tasks" [(ngModel)]="tasks"></app-main> Here is the function call from JavaScript: public tasks; ngOnInit() { this.tasks.click(); } I have attempted using document.getE ...

What is the best way to implement rate limiting or throttling on a Strapi API?

Our company relies on a simple strapi API implemented in node.js and hosted on Heroku. Despite our efforts, we have not been able to find a solution to implement rate limiting, as it appears that Heroku does not offer throttling add-ons and strapi lacks bu ...