3
Hi @TinyTiger I was searching for the same with Script Setup and TypeScript and ended implementing this with Yusuf Kandemir help.
<template>
<q-card>
<q-avatar
color="red"
v-on:click="selectFile()"
>
<q-img
v-bind:src="img"
v-bind:fit="'contain'"
v-bind:ratio="1"
/>
</q-avatar>
<q-file
ref="fileRef"
v-model="fileModel"
style="display: none"
v-bind:max-files="1"
accept="image/*"
v-on:update:model-value="fileOnUpdate"
/>
</q-card>
</template>
<script setup lang="ts">
import { Ref, ref, onUnmounted } from 'vue'
import { QFile } from 'quasar'
const fileModel = ref<File>()
const fileRef = ref() as Ref<QFile>
const img = ref<string>()
function selectFile() {
fileRef.value.pickFiles()
}
function fileOnUpdate(selectedFile: File) {
if (img.value) {
URL.revokeObjectURL(img.value)
}
img.value = URL.createObjectURL(selectedFile)
}
onUnmounted(() => {
if (img.value) {
URL.revokeObjectURL(img.value)
}
})
</script>
3
You can create ref
to q-file
, then from q-btn
call it with file.value.pickFiles()
const { ref, onMounted } = Vue
const app = Vue.createApp({
setup () {
const image = ref(null);
const imageUrl = ref('');
const file = ref(null)
const handleUpload = () => {
if (image.value) {
imageUrl.value = URL.createObjectURL(image.value);
}
}
const handleUploadBtnClick = () => {
file.value.pickFiles()
}
return {
image, imageUrl, handleUpload, handleUploadBtnClick, file
}
}
})
app.use(Quasar)
app.mount('#q-app')
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet" type="text/css">
<link href="https://cdn.jsdelivr.net/npm/quasar@2.4.13/dist/quasar.prod.css" rel="stylesheet" type="text/css">
<div id="q-app">
<div>
<q-file
style="display: none"
v-model="image"
@update:model-value="handleUpload"
ref="file"
></q-file>
</div>
<div>
<q-btn
type="button"
label="Upload Photo"
@click="handleUploadBtnClick"
></q-btn>
</div>
<div>
<q-img
:src="imageUrl"
spinner-color="white"
style="height: 140px; max-width: 150px"
></q-img>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdn.jsdelivr.net/npm/quasar@2.4.13/dist/quasar.umd.prod.js"></script>
Source:stackexchange.com