Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
Making file upload component using Composition API (vuejs3)

I'm trying to use a 'file picker' component globally on my app and getting the 'imageUrl' base64 to manipulate upload on server.

I have the following on my component:

<template>
      <div class="column" style="width: 300px;">
        <q-btn @click="sendEventImage ()" style="margin-top: 16px; margin-bottom: 32px;" outline color="white" text-color="black" label="Procurar imagem" />
        <input style="display:none" ref="EventfileInput" @change="onEventFilePicked" type="file" name="upload" accept="image/*" />
        <q-img class="w-30 h-30" :src="imageUrl" />
      </div>
</template>

<script>

import { defineComponent, ref } from 'vue'

export default defineComponent({
  name: 'PageIndex',
  setup () {
    let imageUrl = ref('')
    let model = ref(null)
    return {
      sendEventImage () {
        console.log('sendEvent preview')
        this.$refs.EventfileInput.click()
      },
      onEventFilePicked (event) {
        const files = event.target.files
        let image = files[0]
        console.log(image)
        let filename = files[0].name
        if (filename.lastIndexOf('.') <= 0) {
          return alert('Por favor adicione um arquivo válido')
        }
        const fileReader = new FileReader()
        fileReader.addEventListener('load', (event) => {
          this.imageUrl = fileReader.result
          console.log('setimageUrl', this.imageUrl)
        })
        fileReader.readAsDataURL(files[0])
      },
      imageUrl,
      model
    }
  }
})
</script>

How can i use this component in every component of my app and also get the "imageUrl" parameter on my setup () to use this parameter ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You'll have to emit an event so the parent component can react to it: https://v3.vuejs.org/guide/composition-api-setup.html#accessing-component-properties

Untested:

<template>
      <div class="column" style="width: 300px;">
        <q-btn @click="sendEventImage ()" style="margin-top: 16px; margin-bottom: 32px;" outline color="white" text-color="black" label="Procurar imagem" />
        <input style="display:none" ref="EventfileInput" @change="onEventFilePicked" type="file" name="upload" accept="image/*" />
        <q-img class="w-30 h-30" :src="imageUrl" />
      </div>
</template>

<script>

import { defineComponent, ref } from 'vue'

export default defineComponent({
    name: 'FileUpload',
    emits: ['imageloaded'],
    setup (props, { emit }) {
        const imageUrl = ref('');
        const EventfileInput = ref(null);
          
        const onEventFilePicked = (event) => {
            const files = event.target.files
            const image = files[0]
            console.log(image)
            const filename = files[0].name
            if (filename.lastIndexOf('.') <= 0) {
              return alert('Por favor adicione um arquivo válido')
            }
            const fileReader = new FileReader()
            fileReader.addEventListener('load', (event) => {
              imageUrl.value = fileReader.result
              console.log('setimageUrl', imageUrl.value)
              emit('imageloaded',imageUrl.value);
            })
            fileReader.readAsDataURL(files[0])
        };
        const sendEventImage = () => {
            console.log('sendEvent preview')
            EventfileInput.click()
        };
        return {
            imageUrl,
            sendEventImage,
            onEventFilePicked
        }
    }
})
</script>

A few remarks on your code which I changed in my example:

  • don't use this in setup()
  • I recommend using const for refs to prevent accidentally overriding them and losing reactivity.
  • you can define template refs like normal refs: https://v3.vuejs.org/guide/composition-api-template-refs.html#template-refs
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda