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`) : ''
}
}
I have the images in the /src/assets/
directory. The error I'm getting in the browser console is:
[Vue warn]: Error in render: "Error: Cannot find module './some-icon.png'."
I'm not sure if this is a webpack config issue, or a problem with the getIconPath function. Anything help is appreciated, thanks!
Considering your JavaScript code is at
/src/components/JobList.vue
and your images are at/src/assets/
, use as follows:It looks like to me that the static assets such as images should be going to /static when webpack builds in dev or prod.
Looking in the config file: vuejs-templates/webpack/blob/develop/template/config/index.js, you have the following configuration (provided you haven't changed anything):
So the src should probably be something like:
EDIT:
Looking further into the configs, in vuejs-templates/webpack/blob/develop/template/build/webpack.base.conf.js, there's a url-loader plugin which should place images into /static/img:
Which could make your src url (depending on how the icons are being loaded):