You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3组件间动态传递图片URL遇404问题求助(路径正确)

Vue3组件传递图片URL动态绑定404问题解决

问题根源

直接传递相对路径字符串时,Vue的构建工具(Vue CLI/Vite)不会把它识别为静态资源处理,打包后资源实际存放路径和你传入的相对路径不匹配,导致404错误。

解决方案

1. Vue CLI环境用require()包裹路径

在父组件调用details方法时,用require()包裹每个图片路径,让Webpack正确解析资源:

<a
@click="
details(
require('../assets/images/references/batiment/batiment-project1.svg'),
require('../assets/images/references/batiment/batimentProject2.svg'),
require('../assets/images/references/batiment/batimentProject3.svg'),
require('../assets/images/references/batiment/batimentProject4.svg')
)
"
>En savoir plus</a>

require()会返回资源打包后的真实URL,传递给子组件后就能正常加载。

2. Vite环境用new URL()处理路径

如果是Vite构建的项目,用new URL()生成正确的绝对资源路径:

<a
@click="
details(
new URL('../assets/images/references/batiment/batiment-project1.svg', import.meta.url).href,
new URL('../assets/images/references/batiment/batimentProject2.svg', import.meta.url).href,
new URL('../assets/images/references/batiment/batimentProject3.svg', import.meta.url).href,
new URL('../assets/images/references/batiment/batimentProject4.svg', import.meta.url).href
)
"
>En savoir plus</a>

import.meta.url代表当前模块的URL,配合new URL()能生成适配打包后的资源路径。

3. 提前在父组件统一处理路径(更整洁)

可以把路径处理逻辑封装成函数,提前在父组件data中处理好再传递:

<script setup>
import { ref } from 'vue'

const image11 = ref('')
const image22 = ref('')
const image33 = ref('')
const image44 = ref('')

// 根据构建工具选择对应的路径处理方式
const getImageUrl = (path) => {
  // Vue CLI环境用下面这行
  return require(path)
  // Vite环境替换成:return new URL(path, import.meta.url).href
}

const details = () => {
  image11.value = getImageUrl('../assets/images/references/batiment/batiment-project1.svg')
  image22.value = getImageUrl('../assets/images/references/batiment/batimentProject2.svg')
  image33.value = getImageUrl('../assets/images/references/batiment/batimentProject3.svg')
  image44.value = getImageUrl('../assets/images/references/batiment/batimentProject4.svg')
  new bootstrap.Modal(document.getElementById("staticBackdrop")).show()
}
</script>

父组件向子组件传递时直接绑定处理好的变量:

<ChildComponent :image1="image11" :image2="image22" :image3="image33" :image4="image44" />

子组件代码无需修改

子组件的props定义和图片绑定保持原样即可:

<template>
  <img class="col-4" width="100%" :src="image2" alt="" />
</template>

<script setup>
defineProps({
  image1: String,
  image2: String,
  image3: String,
  image4: String,
})
</script>

内容的提问来源于stack exchange,提问作者Imen MK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 10:55:20