Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v-binding an image from an object to an img src not working... #42

Closed
rchrdnsh opened this issue Jun 16, 2017 · 29 comments
Closed

v-binding an image from an object to an img src not working... #42

rchrdnsh opened this issue Jun 16, 2017 · 29 comments

Comments

@rchrdnsh
Copy link

Soooo,

...doing this:

screen shot 2017-06-15 at 7 12 40 pm

...from this:

screen shot 2017-06-15 at 7 13 14 pm

...and getting this:

screen shot 2017-06-15 at 7 23 57 pm

The first row in the above pic are from the v-for version and the second row are the static hard coded HTML versions of the same things.

So I dunno why the images are not loading, when all the other data, including the alt stuff is loading...checked the file path of the images, which are fine, so I must be doing something wrong, just don't know what...🤔

Any thoughts are most welcome, thanks! XD

@CodinCat
Copy link
Contributor

Questions should be asked on Stack Overflow or the Vue.js forum. Here is for the issues related to the PWA template.

@rchrdnsh
Copy link
Author

rchrdnsh commented Jun 16, 2017

I can get it to work outside of the vue-pwa template, tho, so i wondered if it was a template problem. I will ask on the forum as well :-)

@ragingwind
Copy link
Contributor

ragingwind commented Jun 16, 2017

v-binding is not related to vue-pwa-tempalte. It's a general question how to make it with vue.je. Vue.js already has great place for this https://forum.vuejs.org/. You look find the right place to ask of this https://forum.vuejs.org/t/v-binding-an-image-from-an-object-to-an-img-src-not-working-in-vue-pwa-template/12754

@rchrdnsh
Copy link
Author

ok, I'll close this one and wait for help there then...

@rchrdnsh
Copy link
Author

I'm re-opening this because I'm thinking the issue might not be with Vuejs, but with the Webpack configuration in the template, although I don't know for sure...

Hi @addyosmani, I'm asking you because I don't know who else put this template together and I don't know if I'm running into a bug or not (it could still easily be me being 'not smart' or something
😬 )...

Anyway, do you think anything in the Webpack config could be causing the issue stated above in the first post? The following snippet is from the webpack.base.conf file

screen shot 2017-06-15 at 10 20 02 pm

I've been seeing mentions of this piece in other threads similar to this one, although I don't understand what's going on in the code at all, or how to fix anything. This is the file path...

screen shot 2017-06-15 at 10 23 03 pm

Again, apologies if this is the wrong place for whatever the issue is...I have asked on the Vue JS forum as well, but so far it's been crickets over there...

@rchrdnsh rchrdnsh reopened this Jun 16, 2017
@ragingwind
Copy link
Contributor

ragingwind commented Jun 16, 2017

I hope it helps you

as you said, it's relevant that how to use webpack and configurations not vue-template. I would give a recommendation you to refer to many of references and guides in the net. templates generated by vue init has a very basic skeleton structure so you should understand that it makes better one

It looks that url-loader can't fine image resource properly

@rchrdnsh
Copy link
Author

Woo Hoo!!! @LinusBorg solved it for me...it was a webpack requirement. Here is his message on the Vuejs Forum:

"You have to wrap the path in require('.. /../.....') to let webpack know that it should handle this strong as a dependency.

The url-loader that is configured for image file types (is you use our template) will then convert this path that is relative to the component file into a path that is relative to the build files, and it will copy the image to /dist/assets..."

Then I wrote back:

"Holy Scooby Snacks! It worked, thank you!!!

I'm now wondering, however, if there is a better pattern to access images dynamically. Is it possible to not have to specify the backwards travel through the file path...

require('../../assets/images/team/richard-nash.jpg')

...and simply ask for the image from the assets folder?...

@assets/images/team/richard-nash.jpg'

...so worrying about exact file path position relative to other files and folders is made irrelevant? Is that a thing that is possible, or must we use require and mentally track file paths up and down the apps directory structure?

Thank you, again, @LinusBorg ! XD

R"

Anyway, at the very least the issue is solved for now, and happy to close this one and dive deeper into webpack over the weekend. Thank you for your patience @ragingwind with a newb like myself :-)

@kengres
Copy link

kengres commented Aug 25, 2017

@rchrdnsh thank you for opening and reopening this issue. you just saved my arse (one year later) on a problem I spend 30min figuring out. thanks a lot!!! 👍

@edencorbin
Copy link

Hey the require('path') worked for me too. I'm new to Vue and find this one odd, what if the image is messing, this would be a compile error I believe.

@julianandreszb
Copy link

julianandreszb commented Jul 11, 2018

Using: Vue 2.0 + Browserify

I had to put the full path to the image and use computed function

Path of Images:

  • www/images/lfpinpad/error.png
  • www/images/lfpinpad/offline.png
  • www/images/lfpinpad/online.png

Path of Component

  • www/src/components/app/AppTopMenu.vue
<template>
   <img v-bind:src="imageSrc" />
</template>

export default {
    data() {
        return {}
    },
    computed: {
        imageSrc: function () {
            return './../../../images/lfpinpad/' + Shared.websocket.websocket_image_status
        }
    }
}

Where Shared.websocket.websocket_image_status is one of:

  • offline.png
  • online.png
  • error.png

@hamzeh010
Copy link

hamzeh010 commented Sep 15, 2018

Remove relative path and user basUrl

 data() {
            return {
             
                baseUrl:window.location.origin
            }
        },

@SarKerson
Copy link

I also met the same problem. The solution given by @rchrdnsh solved the problem.
that is:

...
<img :src='img'>
...
const img = require('../../assets/images/team/richard-nash.jpg')

But I also found another solution, to edit the file webpack.config.js, change the chunkhash to hash

      {
        test: /\.(png|jpg|gif|svg)$/,
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]?[hash:5]'
          }
        }]
      }

@s4n4s
Copy link

s4n4s commented Oct 19, 2018

Hi,
i tried all the solution given but it still dosen't work for me.
I tried loading the images by using require in v-bind:src but nothings happen.

json file:
[ { "title": "Accueil", "content": "Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression. ées 1500, quand un imprimeur", "img_src": "../../assets/img/home/carousel/navy_seals_1.jpg" }, { "title": "Accueil", "content": "Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression. ées 1500, quand un imprimeur", "img_src": "../../assets/img/home/carousel/navy_seals_1.jpg" },
File import

<script> import json from '../../data.json' export default { name: "store", data(){ return { data:json} }} </script>

Loop v-for for display

<div class="iteam_card_container"> <b-col ><div v-for="item in data" class="item_card"> <img :src="item.img_src" /> <div> <b-button class="card_btn" :variant="primary">Ajouter au panier</b-button> <p class="title">{{ item.title }}</p> <p class="card_content">{{ item.content}}</p> </div> </div></b-col> </div>
Thanks for help.

@s4n4s
Copy link

s4n4s commented Oct 19, 2018

Solved.

<img :src=" require(@/assets/img/home/carousel/${item.img_src}) " />
item.img_src is the name of the image file.

@mayank1513
Copy link

Woo Hoo!!! @LinusBorg solved it for me...it was a webpack requirement. Here is his message on the Vuejs Forum:

"You have to wrap the path in require('.. /../.....') to let webpack know that it should handle this strong as a dependency.

The url-loader that is configured for image file types (is you use our template) will then convert this path that is relative to the component file into a path that is relative to the build files, and it will copy the image to /dist/assets..."

Then I wrote back:

"Holy Scooby Snacks! It worked, thank you!!!

I'm now wondering, however, if there is a better pattern to access images dynamically. Is it possible to not have to specify the backwards travel through the file path...

require('../../assets/images/team/richard-nash.jpg')

...and simply ask for the image from the assets folder?...

@assets/images/team/richard-nash.jpg'

...so worrying about exact file path position relative to other files and folders is made irrelevant? Is that a thing that is possible, or must we use require and mentally track file paths up and down the apps directory structure?

Thank you, again, @LinusBorg ! XD

R"

Anyway, at the very least the issue is solved for now, and happy to close this one and dive deeper into webpack over the weekend. Thank you for your patience @ragingwind with a newb like myself :-)

Hi...

Can you please explain how you used require???

@IFMaggie
Copy link

A similar problem has been encountered in a recent project. After reading your article, it has been resolved. Thank you.
The problem is: ”img src='../static/assest/images/index/inst_logo01.png' /> “There is no problem with introducing images.
"img :src='../static/assest/images/index/inst_logo01.png' /> "The src attribute written by the method cannot be parsed.
Solution: "img src='../../assest/images/index/inst_logo01.png' />"

@hoangtranson
Copy link

my solution is using computed

export default {
  props: {
    article: {
      type: Object
    }
  },
  computed: {
    url: function() {
      return `/_nuxt/${this.article.image}`;
    }
  },
}

then use it normally

<img v-bind:src="url" alt="">

@harismann
Copy link

thank you @s4n4s i solved with your solution:

item.img_src is the name of the image file.

but i need add backtick() to solve it like this : <img :src=" require(@/assets/img/home/carousel/${item.img_src}`) " />

@anujpradhaan
Copy link

anujpradhaan commented Sep 2, 2019

so the solution is <img :src="require(PATH/${item.img_src)"/> path can be different in your particular case. Example in my case it was ../assets/img/portfolio.

Note: Remember to put `` not '' inside require. Because github hides them considering its code.

@cornesmith
Copy link

Thanks @rchrdnsh. Three years later this "feature" still persists in webpack and Vue.
In a Vue component just used:

<template>
  <div>
     <img :src="image"/>
  </div>
</template>
...
<script>
    export default {
        data: () => {
            return {
                image: require('../assets/img/thumbnail.jpg'),
            }
        }
  }
</script>

And it works like a charm.

@xrusselx
Copy link

xrusselx commented Jul 29, 2020

Thanks @rchrdnsh. Three years later this "feature" still persists in webpack and Vue.
In a Vue component just used:

<template>
  <div>
     <img :src="image"/>
  </div>
</template>
...
<script>
    export default {
        data: () => {
            return {
                image: require('../assets/img/thumbnail.jpg'),
            }
        }
  }
</script>

And it works like a charm.

Hello @cornesmith! I'll try to use that but an error occurs that says: require is not defined. I'm just a beginner and I'm using vite. And if I'm correct, vite do not use webpack.

@johnSoneka
Copy link

After spending more that four hours looking for the solution it finally worked

Using require() in my array
Thanks to this community

@atheistrepublic
Copy link

Yes require also works for me. Thanks

@Red-Asuka
Copy link

Solved.

<img :src=" require(@/assets/img/home/carousel/${item.img_src}) " />
item.img_src is the name of the image file.

it also works for me. thx

<img
  :src="require(`@/assets/images/${item.img}`)"
  :alt="item.title"
/>

@gcampionpae
Copy link

worked for me too, thanks for this!

@burakhanaksoy
Copy link

burakhanaksoy commented Jun 27, 2021

After spending more that four hours looking for the solution it finally worked

Using require() in my array
Thanks to this community

Thank you~ This solved it for me. @johnSoneka

@kishanvaishnav
Copy link

kishanvaishnav commented Sep 13, 2021

Solved.

<img :src=" require(@/assets/img/home/carousel/${item.img_src}) " />
item.img_src is the name of the image file.

i'm using this but not solved

I am facing this issue

./src/components/Home.vue?vue&type=template&id=8dc7cce2 (./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/vue-loader-v16/dist/templateLoader.js??ref--6!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/components/Home.vue?vue&type=template&id=8dc7cce2)
Module not found: Error: Can't resolve '@/assets/image/${item.imageArray}' in 'C:\Users\TFVFGHGFHJG\Desktop\vue-projects\allevahomecare\src\components'

@Barnabas02
Copy link

Using the require('') helped me solve the problem.
Thank you

@mullermad
Copy link

guys if u are using vite
// Function to get the URL of an image
const getImageUrl = (filename) => {
// Correct usage with import.meta.url
return new URL(../assets/img/${filename}, import.meta.url).href;
}; and acess in :src="getImageUrl(movie.poster)" works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests