Home » vue » Where should I put upload function in Vue components?

Where should I put upload function in Vue components?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have an ImageUploader component through which I upload pictures in my project.

Currently, it is necessary to use different endpoints for uploading, and I want to refactor this component.

I see two ways:

  1. I can move upload method to the parent component using this.$emit(onUpload, files), and in the parent component: <ImageUploader @onUpload='uploadHandler'/>

  2. Pass action as prop in the component that will be used for loading
    <ImageUploader :uploadAction="AProjectMedia.UPLOAD_IMAGE" />, and in the component, use it like this: this.$store.dispatch(uploadAction, files)

How correct are my options? and what options are there still?

Answers:

Number one seems better since it keeps your component clean for a single purpose (uploading the file). Any side effect should probably be handled by the parent. This way, the parent components (which are different) bear the responsibility for the different functions.

Another option is to call the action directly from the child component, though this could be an issue if you’re aiming for reusability.

###

I would say number 1 is better. According to best practices, communication between components happens in two ways:

Parent -> Child via props;

Child -> Parent via events;

For more info, see this article. Even when I’m using Vuex, I prefer this communication pattern instead of call actions/getters from child component.