Ryoidenshi Aokigahara
Ryoidenshi Aokigahara

Reputation: 168

Using image src from asset variables

I have a problem with images recently. Everything is ok until you have to show a list of images on the page.

The problem is that when we directly give an src for image with hardcoded string, it works with a url like ~/assets/any-image.png. But if I try to move url into any variable / object / array, I have to specify the :src="myVariable" which contains the URL.

The code for example:

<template>
  <div>
    Problem with images
    <img :src="image.url" alt="">
    <img :src='require(image.url)' alt="">
  </div>
</template>

<script>
export default {
  data () {
    return {
      image:
        {
          url: '~/assets/icon.png',
          type: 'asset'
        }
    }
  }

}
</script>

Here I tried using assets with ~ and @, also with and without slash. Of course the image exists in assets folder, but since the src url is provided via any variable (not directly), the assets url is not served and as a result the image url looks like host:port/~/assets/... which doesn't exist on the server.

In this example I've got an idea to replace image url with an object containing the url and its type (asset/static) and make checks if type asset, then use require(variable) but got the problem that "Cannot find module '~/assets/icon.png'"

Has anybody solved this problem?

Upvotes: 1

Views: 3671

Answers (2)

Dan
Dan

Reputation: 63129

You need to use require when binding to an asset variable image. For example:

<img :src="url">
url: require('@/assets/icon.png')

If your json contains only the filename, you can place require in the template:

<img :src="require('@/assets/' + url)">
url: 'icon.png'

Upvotes: 3

Ryoidenshi Aokigahara
Ryoidenshi Aokigahara

Reputation: 168

Thanks to Dan with his answer I've got a final solution which is universal: Image contain it's link and type:

image: {
  url: '/any-asset-folder/image.png'
  type: 'asset'
}

Then with ternary operator result is

<img
  :src="image.type === 'asset' 
    ? require('@/assets'+image.url) 
    : image.url"
>

In this way I've got images working both if they are from assets or static or external :)

Upvotes: 1

Related Questions