Vue中如何从本地assets渲染图片?本地图片加载404问题求助
解决Vue + Vite中本地Assets图片作为背景图404的问题
问题原因
Vite的静态资源处理机制下,直接写在字符串里的相对路径(比如../assets/img1.png)不会被构建工具解析,导致运行时请求错误路径,返回404。
解决方案1:在Pinia中直接引入图片资源
修改Pinia状态定义,通过import引入图片,让Vite自动处理资源路径:
import { defineStore } from 'pinia' // 引入本地图片资源 import img1 from '../assets/img1.png' import img2 from '../assets/img2.png' import img3 from '../assets/img3.png' export const useProductsStore = defineStore('productsStore', { state: () => ({ products: [ { id: 0, name: 'iPhone 6s Plus 16GB', salePrice: 649, price: 1000, currency: '$', imgUrl: img1 // 使用引入后的图片对象 }, { id: 1, name: 'iPad Pro 32GB', salePrice: 600, price: 800, currency: '$', imgUrl: img2 }, { id: 2, name: 'MacBook Pro', salePrice: 0, price: 8000, currency: 'PLN', imgUrl: img3 } ] }) })
组件代码无需修改,此时imgUrl已为Vite处理后的正确路径。
解决方案2:在组件中动态解析路径
若不想修改Pinia数据源,可在组件内用new URL()动态构建正确资源路径:
修改组件中背景图的样式绑定:
<div class="product-card__img" :style="{ backgroundImage: `url(${new URL(product.imgUrl, import.meta.url)})` }" ></div>
说明
import.meta.url代表当前模块的URL,new URL(path, base)会基于当前模块位置解析出正确的资源绝对路径,Vite构建时会自动处理该路径,确保资源加载正常。
额外注意事项
- 确认图片确实放在
src/assets/目录下(标准Vue+Vite项目结构) - 不要在
:style的字符串中使用Vue双大括号插值({{}}),绑定对象结合模板字符串的方式更可靠
内容的提问来源于stack exchange,提问作者Michał
相关产品推荐
相关产品推荐

