0

I have been trying to import an image asset relative path to a banner component. The following works just fine.

<b-img src="~/static/images/carousel1.jpg" alt="Samyojya Consultants banner"/>

On html, I see it rendered as this

<div class="card-body"><img src="/_nuxt/static/images/carousel1.jpg"...

But the v-bind style representation like this does not bundle the image

<b-img :src="imgSrc" :alt="title+'banner'"/>

I can see on the html that imgSrc value is passing on but not compiled by asset processor

<div class="card-body"><img src="~/static/images/carousel1.jpg" ...

Is there a way we can explicitly trigger this compilation? require doesn't seem to work too.

<b-img :src="require(imgSrc)" :alt="require(title)+'banner'"/>

This dynamic style is needed for my use-case.

kissu
  • 40,416
  • 14
  • 65
  • 133
Naveen Karnam
  • 433
  • 2
  • 9
  • 26

3 Answers3

1

Create a computed prop (or method, or similar) to resolve (require) the relative path:

export default {
  data() {
    return {
      title: 'Image title'
    }
  },
  computed: {
    imgSrc() {
      // Relative to component directory
      return require('./image.png')
    }
  }
}

And then reference that in your template:

<b-img :src="imgSrc" :alt="title+' banner'"/>
Troy Morehouse
  • 5,320
  • 1
  • 27
  • 38
1

On the calling (parent) template, I used this

<banner :imgSrc="imgSrc" ...

And the data export in parent like this.

export default {
  data: function(){
    return {
      imgSrc:require('../static/images/carousel2.jpg')
    }
  },
... 

In the child component where the banner is drawn.

<b-img :src="imgSrc"...

Note: require needs a relative path (../static) from components/pages while without require we can use absolute (~/static).

kissu
  • 40,416
  • 14
  • 65
  • 133
Naveen Karnam
  • 433
  • 2
  • 9
  • 26
0
<b-img :src="require('../static/images/carousel1.jpg')" alt="Samyojya Consultants banner"/>
kissu
  • 40,416
  • 14
  • 65
  • 133
Haresh
  • 54
  • 3
  • Yes. This works similar to _src="../static/images/carousel1.jpg"_ . The challenge here is to take it through a prop variable like so _:src="require(imgSrc)"_ doesn't work! It looks so simple but tricky! – Naveen Karnam Nov 06 '19 at 10:20
  • Also, I tried placing require at parent component (which is calling the banner component) like this _ – Naveen Karnam Nov 06 '19 at 10:41