Vue.js dynamic image paths not loading

2019-07-15 02:11发布

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!

2条回答
太酷不给撩
2楼-- · 2019-07-15 02:53

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}`) : ''
    }
}
查看更多
做自己的国王
3楼-- · 2019-07-15 03:01

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):

// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',

So the src should probably be something like:

<img src="/static/whatEverMyIconIs.png"/>

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:

 {
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    options: {
      limit: 10000,
      name: utils.assetsPath('img/[name].[hash:7].[ext]')
    }
  },

Which could make your src url (depending on how the icons are being loaded):

<img src="/static/img/whatEverMyIconIs.png"/>
查看更多
登录 后发表回答