Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...