Adding static images to a component, they do not appear

This is a code snippet my component

<img :src="logo">

export default {
  name: 'NavbarComponent',
  data: function() {
    return {
      logo: './assets/img/test.jpg'
    }
  }
}

No matter what combination of pathing I use, …/ ./ etc, the image fails to display. Now if I add it as a background in CSS, it works, and this also works

<img src="../assets/img/test.jpg">

but not when I use vue?

Have you tried wrapping it in a require call?

A static src for an <img> gets rewritten by Webpack but for dynamic paths you generally need to use require.

e.g.:

logo: require('../assets/img/test.jpg')
2 Likes
data() {
    return {
      logo: '/img/test.jpg'
    }
  },
1 Like

Thank you, that solved my problem. For multiple images I’m thinking that using require would be tedious?

If you just want files to be copied across to the build output you can put them in the public folder. You wouldn’t include the public part in the final path if you did it that way.

Files in the assets folder are not copied across to the build output directly. They undergo tree-shaking so you need an import or require for them to be included. By default this process also renames the file to include a hash. This hash is useful for caching purposes but it means that you can’t easily guess what the final file path will be. Using require (or import) will give you back the correct path at runtime.

Webpack is reasonably clever about processing require. For example, it can cope with something like this:

require('../assets/img/' + name + '.jpg')

It won’t know exactly what file that matches but it’ll figure out that it’s something in the img folder with an extension of .jpg. All files that meet those criteria will be included in the build.

1 Like

Finaly Solve this way:

Logo

export default {
name: ‘Header’,
data: function() {
return {
logo: require(’…/assets/frontend/images/logo/pis_logo.jpg’)
}
}

}