使用资产变量中的图像src [英] Using image src from asset variables

查看:59
本文介绍了使用资产变量中的图像src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近对图像有疑问.一切正常,直到必须在页面上显示图像列表为止.

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

问题在于,当我们直接为带有硬编码字符串的图像提供src时,它可以与~/assets/any-image.png这样的url一起使用.但是,如果我尝试将url移到任何变量/对象/数组中,则必须指定包含URL的:src="myVariable".

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.

代码例如:

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

在这里,我尝试使用带有~@的资产,以及带斜线和不带斜线的资产.当然,图片存在于资产文件夹中,但是由于src网址是通过任何变量(不是直接提供)提供的,因此不会提供素材网址,因此图片网址看起来像host:port/~/assets/...,该网址在服务器.

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.

在此示例中,我有一个想法,将图像url替换为包含url及其类型(资产/静态)的对象,并检查类型是否为资产,然后使用require(variable),但出现了"Cannot find module '~/assets/icon.png'"的问题

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?

推荐答案

绑定到资产变量图像时,需要使用require.例如:

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

<img :src="url">

url: require('@/assets/icon.png')

如果您的json仅包含文件名,则可以在模板中放置require:

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

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

url: 'icon.png'

这篇关于使用资产变量中的图像src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆