How to reference img in javascript in a vue component when it is loaded with javascript

Viewed 57

File Structure (Webpack)

src
-assets
--img
---myimage.png
-vue
--page
---parent.vue
---component
----child.vue

parent.vue : Here I tried src relative to this component and relative to the child component where the image will be actually loaded.

/** This data is passed to the child component in a loop */
data(){
  return{
    items: [
      { id: 1, src: '../../../assets/img/myImage.png'},
      more items...
    ]
  }
}

child.vue : I get the following error in the console: Error in mounted hook: "Error: Cannot find module '../../../assets/img/myImage.png'"

props: {
  item: {
      type: Object,
      required: true
  }
},
mounted() {
  let element = this.$refs['myelement'];
  let img = new Image();

  img.onload = function(){
      element.insertBefore(this, element.firstChild);
  }
  img.src = require(this.item.src);
},

I have tried every combination possible for the src, I even copied the image file in the component directory and referenced it like myImage.png and ./myImage.png, but the same error appears. What's going on?

1 Answers

Whatever images are placed inside src/assets its moved into static/img/imagename when webpack builds

Try to access those images from browser directly using urls like localhost:8080/static/img/imagename.png

If that is accessible, then rewrite the array with only image file name and prepend with /static/img

Related