0

I'm working on a complex app so I simplify my question.

I have a input component located in the InputFile.vue and a FormFile.vue. I import the InputFile into the Form and after the user uploads a file to the inputfield and send the post request, I want to send the file with axios to the backend.

<!--INPUTFILE-->
<template>
  <input
    :id="props.name"
    :name="props.name"
    type="file"
    :ref="props.name"
  />
</template>
// ...

<script setup>
import { defineProps, ref } from "vue";
const props = defineProps({
  name: String,
});
let fileName = ref("");
<!-- FORMFILE -->

<template>
<div>
  <InputFile name="file" />
</div>
</template>

// ...
<script setup>
import InputFile from "@/components/InputFile";
import { ref } from "vue";

const input_file = InputFile.fileName;

  axios.post('post/file', {
    input_file: input_file
  }).then((res) => console.log(res));

The input_file is not getting the value of the file input (from component InputFile.vue). How can I access the input.value from FormFile ?

Vic Wild
  • 67
  • 1
  • 8

1 Answers1

0

You need to handle the file upload via a method.

A Vue method is an object associated with the Vue instance. Functions are defined inside the methods object. Methods are useful when you need to perform some action with v-on directive on an element to handle events.

    <template>
        <input
            v-on:change="handleFileUpload($event)"
            :id="props.name"
            :name="props.name"
            type="file"
            :ref="props.name"
        />
    </template>
    <script>
    export default {
...
        methods: {
            handleFileUpload(e) {
                e.preventDefault();
                const formData = new FormData();
                formData.append('file', e.target.files[0]);
                axios.post('post/file',
                    formData,
                    {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        },
                    }
                ).then((res) => console.log(res));
            }
        }
    }
    </script>
Shaun
  • 757
  • 1
  • 8
  • 36
  • Ok and then I can trigger the handleFileUpload method from `InputFile.vue` in the FormFile.vue? – Vic Wild Sep 07 '22 at 12:06
  • This answer should help you: https://stackoverflow.com/questions/40957008/how-to-access-to-a-child-method-from-the-parent-in-vue-js#answer-47565763 – Shaun Sep 07 '22 at 13:12