How to load a q-img using a relative path from an object?
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 class="flex flex-center">
<q-item-section
v-for="(plan, index) in plans"
:key="index"
:class="plan.class"
class="col"
>
<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?
1 answer
-
answered 2022-05-05 02:54
Diego Villa
I'm able to dynamically load assets from
/src/assets
in a<q-img>
usingimport.meta.url
, like explained on https://vitejs.dev/guide/assets.html#new-url-url-import-meta-urlconst 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", }, ];
How many English words
do you know?
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
how many words do you know
Powered by Examplum