在文件里引用目录文件下的静态资源图片不显示

发布于:2024-10-18 ⋅ 阅读:(10) ⋅ 点赞:(0)

问题:两种图片路径的指定方式,第一种能展示图片但第二种不能
两个 示例中,图片展示的差异。
在第一个示例中,图片路径是硬编码在 标签的 src 属性中的:

<img src="../../assets/img/header01.png" style="width: 100%; height: auto;" />

这种方式直接指定了图片相对于当前文件的路径,浏览器可以直接加载并显示图片。

然而,在第二个示例中,通过 Vue 的数据绑定功能来动态设置图片路径:

<img :src="scope.row.img" style="width: 100%; height: auto;" />

能展示图片:

<el-table :data="tableData" style="width: 60%;font-size: 16px;color: black">
      <el-table-column prop="img" label="" width="180">
        <template #default="scope">
          <img src="../../assets/img/header01.png" style="width: 100%; height: auto;" />
        </template>
      </el-table-column>
    </el-table>

但问题代码(scope.row.img不能展示图片):
并且,在 tableData 中,为 img 属性分配了一个相对路径字符串:

<div class="bottom-contain">
        <el-table :data="tableData" style="width: 60%;font-size: 16px;color: black">
          <el-table-column prop="img" label="" width="180">
            <template #default="scope">
              <img :src="scope.row.img" style="width: 100%; height: auto;" />
            </template>
{  
  img: '../../assets/img/header1.png',  
  title: '公司電話',  
  contain: '+1233333',  
}

这里的问题可能在于,使用 Webpack 或类似的模块打包器时,相对路径字符串 ‘…/…/assets/img/header1.png’ 可能不会被正确处理为有效的 URL。Webpack 通常期望在 JavaScript 文件中使用 require 或 import 来引入静态资源,这样它就可以将资源路径转换为打包后的输出路径。
所以直接在文件里引用目录文件下的静态资源图片;

import header01 from '../../assets/img/header1.png';
{
    img: header1,
    title: '公司電話',
    contain: '+1233333',
  },

成功拿到图片


网站公告

今日签到

点亮在社区的每一天
去签到