How to add image locally in a Vue?

Viewed 999

I want to add a photo to my project, but for some reason it doesn't want to add locally

Can someone help me how to do this?


template:

  <li v-for="book in books" :key="book.id">
  
             *Some code here*
  
   <img :src="book.image"/> <<<-----Here
 </li>

script:

export default {
   data() {
     return{
       books: [
        image: "../assets/images/a-Dolls-house.jpg"
       ]
     }
   }
}

my directory

1 Answers

Change <img :src="book.image"/> to <img :src="require(book.image)"/>

This will work because the assets folder is not public to the browser. Meaning that when you try to call from the assets folder it cannot find the path specified because the webserver cannot find the assets folder. However by calling require we load the image from the assets folder, and convert it to a base 64 encoded image. Which can be seen by the browser as it is compiled into your chunk.

The other option you have is to move your images folder to the public directory and change your image property to image: "/images/a-Dolls-house.jpg". Then the image will be public and can be accessed from the browser. Without increases your chunk sizes, or increasing your memory overhead, as the images would be linked instead of compiled.

Related