-2

I don't know why this don't work, only the first one charge my img the others no.

1. <img :src="require('../assets/batatas.jpg')" :alt="item.title" />
2. <img :src="'../assets/batatas.jpg'" :alt="item.title" />
3. <img :src="item.img" :alt="item.title" />

I want to use the las one, because i use my own json to charge the iformation, but when I try to put the img only works the first one, in and when i watch the web info i can see the first put this (src="/img/batatas.79e29299.jpg") and the two others put (src="../assets/batatas.jpg") on my web.

I'm starting to use vue and i can't find why this happends.

mesp
  • 1

2 Answers2

0

Welcome to StackOverflow, please make sure you search for similar questions before asking yours. Is always nice to avoid duplicates.

Here it is one question/answer that is similar to yours: Static image src in Vue.js template

You will need the "require" since your object is dynamic and Vue needs to figure out how to map the static asset with the one generated in the build process. That's the one (src="/img/batatas.79e29299.jpg") this random number is the actual end result of the image, that will be visible to the users.

Using the require will be like saying "convert the item.img URL to the actual end-result image URL"

Cassio Cabral
  • 2,652
  • 3
  • 23
  • 37
  • Yes, but the problem is, when i try to do this ` ` vue throw exception "Critical dependency: the request of a dependency is an expression " and in the web console "Error: Cannot find module '@/assets/batatas.jpg'" this is my real problem i try to use `item.img` to load my images, and the others questions its about static string and i wan't to do the same with item.img. Tanks for your help. – mesp Jan 06 '22 at 10:32
  • Try this one then https://stackoverflow.com/questions/40491506/vue-js-dynamic-images-not-working – Cassio Cabral Jan 06 '22 at 10:54
  • @mesp i think the require statement is a complex statement and therefore has to be in the script part and can't be in the template part of vue – h0p3zZ Jan 08 '22 at 03:36
0

I change my json to img: @/assets/batatas.jpg to img: batatas.jpg and then in my component i use <img :src="require('@/assets/' + item.img)" :alt="item.title" /> and this works for me, the cassioscabral answer helps me to understand and trying to my self with this info i solvent this question, thanks to all people who coment this post for help me, I'm really grateful.

mesp
  • 1