如何让vue-loader插值资产网址? [英] How can I get vue-loader to interpolate asset urls?
问题描述
我有一幅具有动态(内插)src
属性的图像.
I have an image with a dynamic (interpolated) src
attribute.
<img src="./{{bar}}.jpg"/>
<img src="./{{bar}}.jpg"/>
如何让vue-loader插值{{bar}}
?
How do I get vue-loader to interpolate {{bar}}
?
推荐答案
我很确定您的代码会引发警告(未引用):
I'm pretty sure that your code throws a warning (not referred it):
[Vue警告]:src ="./{{bar}}.jpg":在"src"属性中进行插值将导致404请求.改用v-bind:src.
[Vue warn]: src="./{{bar}}.jpg": interpolation in "src" attribute will cause a 404 request. Use v-bind:src instead.
因此,您应该绑定值:
<img :src="'/assets/' + bar + '.jpg'">
上面的示例从静态目录assets
加载图像xxx.jpg
,但尚未通过加载器加载.
The above example it loads an image xxx.jpg
from the static directory assets
, but not via loader yet.
要实现此目的,您应该使用动态需求:
To accomplish that, you should use a dynamic require:
<img :src="loadImage(name)">
methods: {
loadImage (imgName) {
return require('./assets/' + imgName + '.jpg')
}
}
注意
不建议目录中包含大量文件,因为Webpack将加载与您的请求匹配的所有文件(对于上例:./assets/*.jpg
).
It is not recommended if the directory contains a large number of files, because the webpack will be load all the files which match your request (for the above example: ./assets/*.jpg
).
这篇关于如何让vue-loader插值资产网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!