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

Vue.js 3中如何从本地JSON动态设置图片的src属性

Fixing Image Loading Issues for Vue 3 Components with Local JSON Data

Hey there! I know being stuck on image loading for two days is frustrating—let’s get this sorted out so your DevJobCard components can display logos from either the assets or static folder without hassle.

Option 1: Loading Images from the assets Folder

The core issue here is that when you reference paths directly from your JSON file, Vue’s build tool (either Webpack for Vue CLI or Vite) doesn’t automatically resolve those relative paths as bundled assets. Here’s how to fix it for both build tools:

For Vue CLI (Webpack-based)

Use require() to tell Webpack to process the image as a bundled asset. Adjust your image tag in DevJobCard like this:

<img 
  :src="require(`@/assets${Job.logo.substring(10)}`)" 
  alt="Company Logo" 
/>
  • @/assets is a default alias pointing to your src/assets folder in Vue CLI.
  • Job.logo.substring(10) strips off the ./assets/ prefix from your JSON path (turning ./assets/logos/scoot.svg into logos/scoot.svg), letting require() locate the correct file and handle bundling.

For Vite

Vite uses new URL() to resolve static assets reliably. Update your image tag to:

<img 
  :src="new URL(`../assets${Job.logo.substring(10)}`, import.meta.url).href" 
  alt="Company Logo" 
/>
  • import.meta.url references the current component’s file URL, and new URL() resolves the relative asset path correctly. Vite will handle bundling and path replacement during the build process.

Option 2: Loading Images from the static Folder (Simpler for Unprocessed Assets)

Your temporary solution works, but we can make it cleaner and more consistent across development and production:

  1. Move your logo files to static/logos/ (create the logos subfolder if it doesn’t exist).
  2. Update your image tag in DevJobCard to:
<img 
  :src="`/static${Job.logo.replace('./assets', '')}`" 
  alt="Company Logo" 
/>
  • This replaces the ./assets segment of your JSON path with /static, converting ./assets/logos/scoot.svg to /static/logos/scoot.svg—a root-relative path that works seamlessly in both environments (Vue copies the entire static folder directly to the build root).

Quick Checks to Avoid Pitfalls

  • Double-check that your folder structure matches the paths in your JSON (e.g., src/assets/logos/scoot.svg exists if you’re using the assets folder approach).
  • If you’re using Vite, ensure you haven’t modified the default asset handling configuration that could break path resolution.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 14:42:47