Vue.js 3中如何从本地JSON动态设置图片的src属性
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" />
@/assetsis a default alias pointing to yoursrc/assetsfolder in Vue CLI.Job.logo.substring(10)strips off the./assets/prefix from your JSON path (turning./assets/logos/scoot.svgintologos/scoot.svg), lettingrequire()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.urlreferences the current component’s file URL, andnew 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:
- Move your logo files to
static/logos/(create thelogossubfolder if it doesn’t exist). - Update your image tag in DevJobCard to:
<img :src="`/static${Job.logo.replace('./assets', '')}`" alt="Company Logo" />
- This replaces the
./assetssegment of your JSON path with/static, converting./assets/logos/scoot.svgto/static/logos/scoot.svg—a root-relative path that works seamlessly in both environments (Vue copies the entirestaticfolder 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.svgexists 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

