How to use dynamic local image in vue?

Viewed 887

I'm trying to show dynamic images depending on a selected option (using the template shown below), but when I deploy the app, I think Webpack changes the image filename. How can I prevent this renaming?

<select v-model="geturl">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>
<div v-if="geturl">
    <img
        :src="require(`@/assets/images/${geturl}.jpg`)"
        style="height:250px; width:250px; object-fit:cover;">
</div>

If I change the options in dev mode, I can see the images; but when I deploy the app, the image filename converts to 1.zxc123.jpg.

Folder structure

3 Answers

You can prevent the renaming by simply moving your images to public folder and use absolute paths in the component to import the images.

Then you can use like..

<img :src="`${geturl}.jpg`">



OR if you want to better control the base_url then you can do something like below..

In public/index.html, you need to prefix the link with <%= BASE_URL %>:

<link rel="icon" href="<%= BASE_URL %>favicon.ico">

In templates, you will need to first pass the base URL to your component:

data () {
  return {
    publicPath: process.env.BASE_URL
  }
}

Then:

<img :src="`${publicPath}${geturl}.jpg`">

Images written to the output directory are handled by the file-loader (via the url-loader). Vue CLI configures the file-loader with a filename template of:

'img/[name].[hash:8].[ext]'

In your Vue project config, remove .[hash:8] from the filename template to disable the asset hash:

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.module
      .rule('images')
        .use('url-loader')
          .loader('url-loader')
          .tap(options => {
            // file-loader is the fallback loader
            options.fallback.options.name = 'img/[name].[ext]'
            return options                             
          })
  }
}

you should put the image in the public/images (images need to be created) directory, because it will not be compiled by webpack. vue2 is placed in the static/images directory. If you don't want to do this, then you need to require to import the image, because then you can get the correct image path after webpack is compiled.

Example:

...
  data: {imgs: [require('../assets/images/1.png'),require('../assets/images/1.png')]}
...
Related