Vuejs image src dynamic load doesn't work
Asked Answered
D

2

5

I just started using Vue.js and Vue CLI and i'm facing an issue, i don't understand why i can't set the image dynamically from the scope but i can do it writing it directly in the HTML, obj.img is a string with @/assets/logo.png value too. I have a timeout faking an ajax call, but the browser does not resolve properly the routes for the image.

<div slot="media">
        <img :src="obj.img"> <!-- http://localhost:8080/@/assets/logo.png -->
        <img src="@/assets/logo.png"> <!-- http://localhost:8080/img/logo.82b9c7a5.png -->
</div>

Also, why are the routes different? Any ideas?

Darra answered 10/10, 2018 at 22:31 Comment(3)
try this ./assets/logo.png in you data object propertyAnalytic
Because the packer is not using require under the hood on a computed property. Check the first answer under the first related question on the right ---->Comply
` <v-img :src="require(@/assets/ + items.image)" height="200px"></v-img>` this one also solved the problemVega
C
8

So the real fix would be this:

:src="getImage(obj.img)"

getImage(path) {
  return require(path)
}

You can read more about it in this response from Evan, the creator of Vue

Comply answered 10/10, 2018 at 22:39 Comment(2)
Apparently not possible to pass only a variable to require, so one of the solutions might be huge switch-case: github.com/facebook/react-native/issues/… Also return require(path + '') seems to be working.Garderobe
` <v-img :src="require(@/assets/ + items.image)" height="200px"></v-img>` this one also solved the problemVega
W
0

Good!

Like @Ohgodwhy showed, Vue don't get the image path directly.

That's the way to get set an image src:

<v-img max-height="150" max-width="250" :src="getImage()"></v-img>

and then, in methods, you need a:

methods: {
    getImage() {
      return require("./logo.png");
    },
  },

And it's done! I'm a beginner and I got a lot to do with it.

Warplane answered 27/4, 2022 at 18:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.