Vue cli 3 项目,图像路径中的动态 src 不起作用 [英] Vue cli 3 project ,dynamic src in image path not working
问题描述
我在 vue 组件中引用图像 url
I am referencing an image url in a vue component like
<img alt="Vue logo" src="~statics/reports/logo.png">
这有效
但在尝试时
<img alt="Vue logo" :src="getURL()">
data() {
return { imgPath: "~statics/reports/logo.png" };
},
methods: {
getURL() {
//
// console.log(path)
return (this.imgPath)
}
},
失败
我的文件夹结构是
在第一种情况下,路径被解析为
In the first case the path is resolved to
http://localhost:8081/img/logo.82b9c7a5.png
并由开发服务器自动提供
and served automatically by the dev server
路径在第二种情况下没有解析它仍然是 http://localhost:8081/~statics/reports/logo.png
The path is not resolved in the second case
it remains http://localhost:8081/~statics/reports/logo.png
我正在使用 vue cli 3 为 webpack 生成的默认配置.
I am using vue cli 3 generated default config for webpack .
我不想对像 ../images/这样的所有图像使用相对路径,因为它会变得更加冗长.我试过 require(pathVariable) 也不起作用当 url 是动态的时,请帮助解析 img 路径,即资产名称来自服务器,我在方法或计算中附加路径并使用 :src 动态绑定来提供它
I do not want to use relative paths for all images like ../images/ as it makes it more verbose. I have tried require(pathVariable) that too does not work Please help with resolving the img path when the url is dynamic ie asset name comes from server and i append a path in a method or computed and use :src dynamicbinding to serve it
推荐答案
第二种方法失败,因为~"尝试从 node_modules 获取此资产.您可以在此处阅读有关处理资产的更多信息:https://cli.vuejs.org/guide/html-and-static-assets.html#relative-path-imports.
The second way fails because "~" try to get this asset from node_modules. You can read more about handling assets here: https://cli.vuejs.org/guide/html-and-static-assets.html#relative-path-imports.
要修复它,只需使用如下所示的 require:
To fix it just use require like below:
data() {
return {
imgPath: require('@/statics/logo.png')
}
}
.. 或直接在模板中:
..or directly in template:
<img alt="Vue logo" :src="require('@/statics/logo.png')">
这篇关于Vue cli 3 项目,图像路径中的动态 src 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!