3

I've been trying to pass a prop to a component, which is a URL to an image for Section component to update v-bind:src of dom img tag, but somehow the image does not show up.

I can't see what's wrong.

File: App.vue

<template>
  <div id="app">
    <Section img="../assets/linux.png" />
  </div>
</template>

<script>
import Section from "./components/Section.vue";

export default {
  name: "app",
  components: {
    Section
  }
};
</script>

File: Section.vue

<template>
  <div>
    <img :src="img" />
  </div>
</template>

<script>
export default {
  props: {
    img: String
  }
};
</script>
HMilbradt
  • 3,980
  • 16
  • 31
  • @ambianBeing, No, there is no need to bind the `img` prop. In fact, what you've posted would break. Since OP is passing a string and no reactivity is needed, there is no need to bind. ***If*** the OP were to choose to bind the prop, they would have to quote the image source like this : `
    `, but the whole thing is quite unnecessary.
    – Vince Oct 06 '19 at 17:33
  • @Vince Yeah u're right! meant exactly that url string should be in reactive property like data or computed and then bind. Guess it came out pretty wrong. – ambianBeing Oct 06 '19 at 17:35
  • @Vince only reason i bind because of an error that's given if you do it with only: and i've tried the following too but to no be given the same error. I want to pass by prop, the url path to image and process that string to />. By any means. – Andre Campos Oct 06 '19 at 19:25
  • 2
    Try `:img="require('../assets/linux.png')"` – Phil Oct 07 '19 at 00:17
  • 1
    Possible duplicate of [How to import and use image in a Vue single file component?](https://stackoverflow.com/questions/45116796/how-to-import-and-use-image-in-a-vue-single-file-component) – Phil Oct 07 '19 at 00:28

1 Answers1

0

I suspect that the issue is due to the relative path you are using. I assume that ../assets/linux.png resolves to the right image URL with respect to App.vue, but it actually needs to resolve to the right image with respect to your <Section> component.

Based on what I can tell from the code you've shared, It seems like you can solve this by updating App.vue as follows:

<template>
  <div id="app">
    <Section img="../../assets/linux.png" />
  </div>
</template>

...

I should, however, point out that you are getting absolutely no benefit from passing the image source as a prop like this. Since it is not bound to a reactive data property in App.vue, you may as well just omit that prop altogether.

Vince
  • 3,207
  • 1
  • 17
  • 28
  • This does not seem to work, i've tried what you said. I want to pass the path to the image by prop because i don't know any other way of passing a string with absolute path or just a path to the image which i don't want to update inside of the Section component. – Andre Campos Oct 06 '19 at 19:21