Using image src from asset variables

假如想象 提交于 2021-02-01 04:48:23

问题


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?


回答1:


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'



回答2:


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 :)



来源:https://stackoverflow.com/questions/65128896/using-image-src-from-asset-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!