使用来自资产变量的图像 src [英] Using image src from asset variables
问题描述
我最近在处理图像时遇到问题.一切正常,直到您必须在页面上显示图像列表.
问题是,当我们直接为带有硬编码字符串的图像提供 src
时,它可以使用像 ~/assets/any-image.png
这样的 url.但是,如果我尝试将 url 移动到任何变量/对象/数组中,我必须指定包含 URL 的 :src=myVariable"
.
代码示例:
<div>图片有问题<img :src="image.url";alt="><img :src='require(image.url)' alt="">
模板><脚本>导出默认{数据 () {返回 {图片:{url: '~/assets/icon.png',类型:'资产'}}}}
在这里,我尝试使用带有 ~
和 @
的资产,也有带斜线和不带斜线的.当然,图像存在于 assets 文件夹中,但是由于 src
url 是通过任何变量(不是直接)提供的,因此不会提供 assets url,因此图像 url 看起来像 host:port/~/assets/...
在服务器上不存在.
在这个例子中,我有一个想法,用一个包含 url 及其类型(资产/静态)的对象替换图像 url,并检查是否类型资产,然后使用 require(variable)
但是遇到"Cannot find module '~/assets/icon.png'"
有人解决过这个问题吗?
绑定到资产变量图像时需要使用require
.例如:
url: require('@/assets/icon.png')
如果你的 json 只包含文件名,你可以将 require
放在模板中:
<img :src=require('@/assets/' + url)">
url: 'icon.png'
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?
You need to use require
when binding to an asset variable image. For example:
<img :src="url">
url: require('@/assets/icon.png')
If your json contains only the filename, you can place require
in the template:
<img :src="require('@/assets/' + url)">
url: 'icon.png'
这篇关于使用来自资产变量的图像 src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!