My Vue 3 / TypeScript app is using Quasar. I have an object holding the relative path to my images, and I'm trying to use that to load the relative path for a quasar q-img
.
Here is the example code:
<template>
<q-page >
<q-item-section
v-for="(plan, index) in plans"
:key="index"
:
>
<q-img :src="plan.imageSrc" style="margin: auto; max-width: 64px" />
</q-item-section>
</q-page>
</template>
<script setup lang="ts">
const plans = [
{
imageSrc: "~/src/assets/paper-plane.png",
monthlyPrice: "699",
class: "starter",
},
{
imageSrc: "~/src/assets/airport.png",
monthlyPrice: "2,789",
class: "growth",
},
];
</script>
It should display the image at the relative path found at plan.imageSrc
but no images are shown.
And the console also throws these errors:
http://localhost:8080/~/src/assets/paper-plane.png 404 (Not Found)
http://localhost:8080/~/src/assets/airport.png 404 (Not Found)
Also I tried using require
as per below, and it also does not work:
<q-img :src="require(plan.imageSrc)" style="margin: auto; max-width: 64px" />
It throws console errors like this:
Error: Cannot find module '~/src/assets/paper-plane.png'
What am I doing wrong?
CodePudding user response:
I'm able to dynamically load assets from /src/assets
in a <q-img>
using import.meta.url
, like explained on https://vitejs.dev/guide/assets.html#new-url-url-import-meta-url
const plans = [
{
imageSrc: new URL('../assets/paper-plane.png', import.meta.url).href,
monthlyPrice: "699",
class: "starter",
},
{
imageSrc: new URL('../assets/airport.png', import.meta.url).href,
monthlyPrice: "2,789",
class: "growth",
},
];