jingman
jingman

Reputation: 405

How can I get vue-loader to interpolate asset urls?

I have an image with a dynamic (interpolated) src attribute.

<img src="./{{bar}}.jpg"/>

How do I get vue-loader to interpolate {{bar}}?

Upvotes: 3

Views: 1605

Answers (2)

Storm
Storm

Reputation: 4445

In attribute interpolation is not allowed, use v-bind instead

https://v2.vuejs.org/v2/guide/syntax.html#Attributes

Upvotes: 0

pespantelis
pespantelis

Reputation: 15382

I'm pretty sure that your code throws a warning (not referred it):

[Vue warn]: src="./{{bar}}.jpg": interpolation in "src" attribute will cause a 404 request. Use v-bind:src instead.

So, you should bind the value:

<img :src="'/assets/' + bar + '.jpg'">

The above example it loads an image xxx.jpg from the static directory assets, but not via loader yet.

To accomplish that, you should use a dynamic require:

<img :src="loadImage(name)">

methods: {
  loadImage (imgName) {
    return require('./assets/' + imgName + '.jpg')
  }
}

NOTE

It is not recommended if the directory contains a large number of files, because the webpack will be load all the files which match your request (for the above example: ./assets/*.jpg).

Upvotes: 4

Related Questions