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

Vuetify+Vite环境下v-img加载本地图片出现404错误求助

解决Vite环境下Vuetify v-img加载本地图片404的问题

在Vite环境中,直接用字符串绑定本地图片路径给v-img的:src会导致路径无法被正确解析,这也是你遇到404的原因。原生<img>的静态src能正常加载是因为Vite会自动处理模板中的静态资源路径,但动态绑定的字符串路径不会触发这个处理逻辑。下面提供两种可行的解决办法:

方法1:通过ES模块导入本地图片

直接用import语句导入图片文件,Vite会自动处理路径并返回正确的资源URL:

<script setup>
// 导入本地图片,得到处理后的URL
import botrightLocal from './assets/images/bottomright.jpg'
const botrightWeb = 'https://quilkin.co.uk/img/bottomright.jpg'
</script>

<template>
  <header>
    <img src="./assets/images/bottomright.jpg" width="125" height="125" />
  </header>
  <main>
    <v-img :src="botrightLocal" width="125" height="125" />
    <v-img :src="botrightWeb" width="125" height="125" />
  </main>
</template>

方法2:使用new URL()构造正确路径

如果需要动态生成图片路径(比如根据变量拼接),可以利用Vite的import.meta.url结合new URL()来构建有效路径:

<script setup>
const imgFileName = 'bottomright.jpg'
// 用new URL拼接路径,Vite会在构建时解析为正确的资源地址
const botrightLocal = new URL(`./assets/images/${imgFileName}`, import.meta.url).href
const botrightWeb = 'https://quilkin.co.uk/img/bottomright.jpg'
</script>

<template>
  <header>
    <img src="./assets/images/bottomright.jpg" width="125" height="125" />
  </header>
  <main>
    <v-img :src="botrightLocal" width="125" height="125" />
    <v-img :src="botrightWeb" width="125" height="125" />
  </main>
</template>

这两种方式都能绕过require(Vite确实不支持CommonJS的require),让v-img正确加载本地图片资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 06:12:27