首页 > 解决方案 > 使用 Vue 和 Webpack 动态加载图像的问题

问题描述

我开始使用 Vue CLI 构建应用程序,并且在组件中有以下代码片段:

<template>
  <div v-loading="loading">
    <el-carousel :interval="4000" type="card" height="350px">
      <el-carousel-item v-for="element in persons" :key="element.id">
            <div class="testimonial-persons">
                <el-avatar :size="80">
                    <img :src="require('@assets/testimonial/'+ element.photo)"> 
                </el-avatar>
                <h3>{{element.name}}</h3>
                <h4>{{element.occupation}}</h4>
                <hr style="width:50%;">
                <p>"{{element.comment}}"</p>
            </div>
      </el-carousel-item>
    </el-carousel>
  </div>
</template>

加载页面时,我请求一个 API,该 API 返回我存储的对象数组persons以迭代模板。

[ 
    { 
        "testimonial_id": "2",
        "persons_id": "1",
        "id": "1", 
        "name": "Tom lima", 
        "occupation": "CEO / Pugmania",
        "comment": "Simply the best customer service and attention to detail.",
        "photo": "20200320193143R7pChVea3IkmujRRmS.png" 
    },

]

一切正常,问题在于图像加载。

在此处输入图像描述

当我手动输入图像名称时,它可以工作。

  <img src="@assets/testimonial/20200320193143R7pChVea3IkmujRRmS.png"> 

有谁知道如何解决?

标签: javascriptvue.jswebpackvuejs2vue-cli

解决方案


/您的模板是正确的,只是您缺少@. 它应该是:

<img :src="require('@/assets/testimonial/' + element.photo)">

这也是手动使用所必需的,因此当您将其转换为动态路径时,您可能会忽略它。


推荐阅读