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

Vue中如何传递包含图片路径的Prop?

Fixing Image Prop Display in Vue Components

Hey there! Let's get that image showing up properly. I spot two key issues in your code that are keeping the image from rendering, so let's break down the fixes step by step.

1. Correct the v-bind Syntax in Header.vue

Your current :src={image} uses object syntax (which would pass { image: image } as the src value), but we just need to bind the prop value directly. Replace that line with:

<img :src="image" alt="Vue logo" />

The double quotes around image tell Vue to evaluate it as a prop, not a string literal.

2. Resolve Static Asset Path Handling

When you pass a relative path like ../assets/logo.png as a plain string prop, Webpack (used under the hood in Vue CLI) doesn't process it as a static asset. That means the browser tries to load the path relative to the current page URL, not your project's asset folder. There are two clean ways to fix this:

In App.vue, use require() to let Webpack resolve the asset path, and bind the result to the image prop (note the colon :image to pass a JavaScript expression instead of a string):

<Header :image="require('../assets/logo.png')" />

Webpack will replace this with the actual URL of the bundled image, ensuring it loads correctly.

Option 2: Use a Computed Property in the Child Component

If you prefer to keep the path string in the prop, you can process it in Header.vue with a computed property:

<template>
  <div class="div-box">
    <img :src="imageUrl" alt="Vue logo" />
  </div>
</template>

<script>
export default {
  name: "Header",
  props: ["image"],
  computed: {
    imageUrl() {
      // Resolve the path relative to the child component's location
      return require(`${this.image}`);
    }
  }
};
</script>

Just make sure the relative path you pass from App.vue is correct relative to Header.vue's file location.

Full Working Code Examples

App.vue

<template>
  <div id="app">
    <Header :image="require('../assets/logo.png')" />
  </div>
</template>

<script>
import Header from './components/Header.vue';

export default {
  name: 'App',
  components: {
    Header
  }
};
</script>

Header.vue

<template>
  <div class="div-box">
    <img :src="image" alt="Vue logo" />
  </div>
</template>

<script>
export default {
  name: "Header",
  props: ["image"],
};
</script>

This should get your Vue logo displaying as expected! The core idea is that Vue CLI's Webpack setup needs to process static assets via require() or import to generate the correct URLs for production and development.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 01:19:05