Tarcísio Melo
Tarcísio Melo

Reputation: 85

Vue.js v-bind:src of an <img> element doesn't showing the image

I have an array of plants. Each plant is an object that includes its name, characteristics, and its image path. I want to show them in a v-for list.

What I've tried:

<img v-bind:src="plant.img">

and this:

<img v-bind:src="'./../../assets/plants/' + plant.name + '.jpg'">

Neither showed the image.

But when I put the image path, like this:

<img src="./../../assets/plants/rose.jpg">

It shows.

It's not v-for error too. What's wrong with my code?

data() {
return {
  plants: [
    { name: 'Rose', sun: 4, water: 6, care: 5, img: "./../../assets/plants/rose.jpg" },
    { name: 'Mint', sun: 8, water: 3, care: 4, img: "./../../assets/plants/mint.jpg" },
    { name: 'Thyme', sun: 7, water: 4, care: 3, img: "./../../assets/plants/thyme.jpg" },
    { name: 'Oregano', sun: 4, water: 6, care: 5, img: "./../../assets/plants/oregano.jpg" },
    { name: 'Lavanda', sun: 8, water: 3, care: 4, img: "./../../assets/plants/lavanda.jpg" },
    { name: 'Patchouli', sun: 7, water: 4, care: 3, img: "./../../assets/plants/patchouli.jpg" },
  ]
}};

Upvotes: 0

Views: 4847

Answers (2)

Nadia Hassouni
Nadia Hassouni

Reputation: 1

I imported my image:

import logo from '@/assets/images/logos/my-logo.png';

My object in operators array:

{
      id: 1,
      name: 'logo',
      logo: logo,
      tpe: 22,
    }

and then use it with v-bind :

            <img :src="operator.logo" height="150" alt="operator logo" />

Upvotes: 0

Kzy
Kzy

Reputation: 508

Hi Try this one maybe its a webpack issue

<img :src="getSrc(plant.name)" v-bind:alt="pic">

And add to methods.

methods: {
    getSrc(name) {
        var images = require.context('../../assets/plants/', false, /\.jpg$/);
        return images('./' + name + ".jpg")
    }
}

https://jsfiddle.net/khenxi/vcf57d0f/

Upvotes: 3

Related Questions