torokakos98
torokakos98

Reputation: 31

Vue JS: How to v-bind image source?

I'm trying to create a webshop, and having some trouble with loading in different images to different categories. Running the server locally and hard coded some category objects (for now, later it'll be coming from a database) and having all the images in the same folder I set the file name as img attribute, so my "creating my database" looks like something like this:

  created() {
this.categories = [
  {
    id: 1,
    text: 'breed category 1',
    cvalue: 'cat1',
    img: 'king-charles-spaniel-resting-head.webp'
  },
  {
    id: 2,
    text: 'breed category 2',
    cvalue: 'cat2',
    img: 'border-collie-dog.webp'
  },
        {
    id: 3,
    text: 'breed category 3',
    cvalue: 'cat3',
    img: 's960_Webp.net-resizeimage__2_.jpg'
  },...

Then I passed the objects to the child component and tried to v-bind the img attribute into the src tag:

<img v-bind:src="'../assets/categ/'+category.img" />

When inspecting the source code, I can see that the binding was successful because the full root appears there (src="../assets/categ/king-charles-spaniel-resting-head.webp"). But the app is not recognizing the root at all and returns with 404 file not found. (When setting the src attribute manually, in inspect mode the following root appears and can load the image: src="/img/border-collie-dog.4ca9975d.webp")

I've also attached an image: the first one is the v-binded root, the second one is when I set the src manually. Image

I hope my explanation was clear enough (I'm quite newbie to development), thank you for the help in advance!

Upvotes: 0

Views: 1183

Answers (1)

Mojtaba
Mojtaba

Reputation: 651

you can use like this. @ reference to src folder:

<img :src="`@/assets/categ/${category.img}`">

Upvotes: 2

Related Questions