I have a problem with images recently. Everything is ok until you have to show a list of images on the page.
The problem is that when we directly give an src
for image with hardcoded string, it works with a url like ~/assets/any-image.png
. But if I try to move url into any variable / object / array, I have to specify the :src="myVariable"
which contains the URL.
The code 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>
Here I tried using assets with ~
and @
, also with and without slash. Of course the image exists in assets folder, but since the src
url is provided via any variable (not directly), the assets url is not served and as a result the image url looks like host:port/~/assets/...
which doesn't exist on the server.
In this example I've got an idea to replace image url with an object containing the url and its type (asset/static) and make checks if type asset, then use require(variable)
but got the problem that "Cannot find module '~/assets/icon.png'"
Has anybody solved this problem?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…