Ajaya Bajracharya
Ajaya Bajracharya

Reputation: 39

Vue dynamic image from assets

Below is my file structure

Project

|-src
  |-assets
    |-images
----->|-logo.png
  |-components
    |-json
----->|-data.json
    |-mainComp
----->|-exp.vue

Now here is my data.json code

"Experience": {
    "0": {
      "sectionTitle": "Awards",
      "sectionContent": {
        "0": {
          "articleTitle": "Adobeedu",
          "articleValue": "2019 Early Bird",
          "articleDate": "Acheived on 2019",
          "image": true,
          "articleImgPath": "../../assets/images/logo.png",
          "articleAlt": "AdobeEdu Early Bird Award"
        }
      }
    }
}

and here below is the code of the exp.vue

<template>
  <div>
    <section class="exp__section" v-for="(data, index) in jsonTitle" :key="index">
      <h5>{{data.sectionTitle}}</h5>
      <article
        v-for="(items, idx) in data.sectionContent"
        v-bind:class="{'content__box':true, 'contains__image':(items.image === true)}"
        :key="idx"
      >
        <h6>{{items.articleTitle}}</h6>
        <div class="image__row">
          <div class="image__box">
            <!-- <img :src="items.articleImgPath" :alt="items.articleAlt" /> -->
          </div>
          <h3>{{items.articleValue}}</h3>
        </div>
        <p>{{items.articleDate}}</p>
      </article>
    </section>
  </div>
</template>
<script>
import json from "@/components/json/english.json";
export default {
  name: "ExperienceSection",
  data() {
    return {
      jsonTitle: json.Experience
    };
  }
};
</script>

Now src does get the value: ../../assets/images/logo.png but the images don't load up. I thought maybe I am not accessing the file structure properly so I tried ./, ../, ../../../, ../../../../ but I think this may not be the problem, and I may need something to load the image after all.

Upvotes: 1

Views: 993

Answers (1)

Dan
Dan

Reputation: 63059

It happens because Vue CLI uses Webpack to bundle the assets folder, and this bundling renames the files/path. So when binding to an asset source, the easiest way to overcome this is to use require in the template and hardcode the assets path and any subpath. For example

<img :src="require('@/assets/images/' + items.articleImgPath)" :alt="items.articleAlt">

Remove the path from the variable and only use the filename:

"articleImgPath": "logo.png",

This also keeps the JSON clean of path names.

Upvotes: 2

Related Questions