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> 
5
  • @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 : <Section :img="'../assets/linux.png'" />, but the whole thing is quite unnecessary. Commented Oct 6, 2019 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. Commented Oct 6, 2019 at 17:35
  • @Vince only reason i bind because of an error that's given if you do it with only: <img src="img" /> 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 <img src=<target> />. By any means. Commented Oct 6, 2019 at 19:25
  • 2
    Try :img="require('../assets/linux.png')" Commented Oct 7, 2019 at 0:17
  • 1
    Possible duplicate of How to import and use image in a Vue single file component? Commented Oct 7, 2019 at 0:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.