首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >V-将对象中的图像绑定到img源不起作用

V-将对象中的图像绑定到img源不起作用
EN

Stack Overflow用户
提问于 2019-02-27 03:39:41
回答 2查看 531关注 0票数 2

我试图以动态方式将对象的URL绑定到我的组件,但它不起作用。只有当我使用require并且直接链接它时,它才起作用,如下所示:"v-bind:imagem="/home/thalys/Documentos/Dev/CodeX/santuarioec/src/imgs/anuncio.png"",或者如果我放置相对路径,如'../imgs/anuncio.png''@/imgs/anuncio.png'

代码语言:javascript
复制
<template>
   <div>
      <site-template>
         <div class="anuncio">
            <anuncio v-for="anuncio in anuncios" v-bind:key="anuncio.id" v-bind:imagem="anuncio.imagem">

            </anuncio>
         </div>

      </site-template>
   </div>
</template>

<script>
import SiteTemplate from '@/templates/SiteTemplate'
import Anuncio from '@/components/anuncio/Anuncio'

export default {
    name: 'Home',
    components: {
       SiteTemplate,
       Anuncio
    },
    data () {
       return {
          anuncios: [
             { "id": 1, "imagem": "/home/thalys/Documentos/Dev/CodeX/santuarioec/src/imgs/anuncio.png" },
             { "id": 2, "imagem": "/home/thalys/Documentos/Dev/CodeX/santuarioec/src/imgs/anuncio.png" },
             { "id": 3, "imagem": "/home/thalys/Documentos/Dev/CodeX/santuarioec/src/imgs/anuncio.png" },
             { "id": 4, "imagem": "/home/thalys/Documentos/Dev/CodeX/santuarioec/src/imgs/anuncio.png" },
             { "id": 5, "imagem": "/home/thalys/Documentos/Dev/CodeX/santuarioec/src/imgs/anuncio.png" }
          ]
       }
    }
 }
 </script>

这是我的组件"Anuncio“

代码语言:javascript
复制
<template>
    <div class="anuncio">
        <div class="w3">                
          <img class="img" v-bind:src="imagem"/>
       </div>
    </div>
</template>

<script>
export default {
    name: 'Anuncio',
    props: ['titulo', 'imagem'],
    data () {
        return {
        }
    }
}

</script>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-27 05:48:52

因此,以下是解决方案:

Anuncio组件中,您必须将图像的路径硬编码到require()方法中。因此,您的img HTML标记将如下所示:

代码语言:javascript
复制
<img class="img" v-bind:src="require(`../imgs/${imagem}`)"/>

在包含带有图像名称的路径的数组中,您应该只提供名称和.png。它看起来像这样:

代码语言:javascript
复制
anuncios: [
             { "id": 1, "imagem": "anuncio.png" },
             { "id": 2, "imagem": "anuncio.png" },
             { "id": 3, "imagem": "anuncio.png" },
             { "id": 4, "imagem": "anuncio.png" },
             { "id": 5, "imagem": "anuncio.png" }
          ]

试一试。

票数 2
EN

Stack Overflow用户

发布于 2019-02-27 03:47:07

如果您已经使用vue-cli (https://cli.vuejs.org/)启动了项目,那么在您的/src目录中应该有一个assets文件夹。

imgs文件夹移动到assets文件夹中。将镜像路径重写为@/assets/imgs/anuncio.png (不需要require() )。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54892891

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档