Vue.js 动态图像路径未加载 [英] Vue.js dynamic image paths not loading
问题描述
我正在尝试在单个文件组件中动态加载图像,但出现无法找到模块的错误.我想我正在尝试做与 this SO post 相同的事情,但我不确定我做错了什么.我使用 webpack 模板 来设置我的项目.
I'm trying to load images dynamically within a single file component, but I'm getting an error that the module cannot be found. I think I'm trying to do the same thing as this SO post, but I'm not sure what I'm doing wrong. I used the webpack template to set up my project.
这是我模板中的相关标记:
Here's the relevant markup in my template:
<router-link :to="{ name: 'JobsDetail', params: { slug: job.slug } }">
<span class="icon">
<img :src="getIconPath(job.slug)"/>
</span>
{{ job.title }}
</router-link>
以及我试图从中获取图像的函数:
And the function I'm trying to get the image from:
methods: {
getIconPath (iconName) {
const icons = require.context('../assets/', false, /\.png$/)
return iconName ? icons(`./${iconName}.png`) : ''
}
}
我在 /src/assets/
目录中有图像.我在浏览器控制台中遇到的错误是:
I have the images in the /src/assets/
directory. The error I'm getting in the browser console is:
[Vue 警告]:渲染错误:错误:找不到模块‘./some-icon.png’."
我不确定这是 webpack 配置问题,还是 getIconPath 函数的问题.任何帮助表示赞赏,谢谢!
I'm not sure if this is a webpack config issue, or a problem with the getIconPath function. Anything help is appreciated, thanks!
推荐答案
考虑到您的 JavaScript 代码位于 /src/components/JobList.vue
而您的图像位于 /src/assets/
,使用如下:
Considering your JavaScript code is at /src/components/JobList.vue
and your images are at /src/assets/
, use as follows:
methods: {
getIconPath (iconName) {
return iconName ? require(`../assets/${iconName}`) : ''
}
}
这篇关于Vue.js 动态图像路径未加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!