Lately, I've been experiencing issues with displaying images on my page, specifically when trying to show a list of images.
The problem arises when attempting to store the image URL in a variable or object instead of hardcoding it directly into the src
attribute. When I try to reference the URL using :src="myVariable"
, which contains the URL, it doesn't work as expected.
For example:
<template>
<div>
Problem with images
<img :src="image.url" alt="">
<img :src='require(image.url)' alt="">
</div>
</template>
<script>
export default {
data () {
return {
image:
{
url: '~/assets/icon.png',
type: 'asset'
}
}
}
}
</script>
In this scenario, I have experimented with different variations of referencing assets using ~
and @
, but encountered errors due to the way the image URL is provided via a variable rather than directly.
I attempted to address this issue by creating an object that includes the image URL and its type (asset/static) and then checking if the type is asset before using require(variable)
. However, I ran into an error stating:
"Cannot find module '~/assets/icon.png'"
Has anyone found a solution to this problem?