简体   繁体   中英

get img src from json file using vue js 2

I'm trying to get img src attribute from a json file but the images are not shown and the alternate texts are. I'm sure that the images are found in the directory src/assets and thier names are right.

this is the component:

<template>
  <div>
    <div class="project" :title="title" :image="image" :desc="desc">
      <div class="p-title">{{title}}</div>
      <div class="p-image">
        <img :src="image" :alt="title">
      </div>
      <div class="p-desc">{{desc}}</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AllProjects',
  props: ["title","image","desc"]
}
</script>

And the view:

<template>
  <div class="projects">
    <AllProjects
      v-for="project in projects"
      :key="project.id"
      :title="project.title"
      :image="`@/assets/${project.image}`"
      :desc="project.desc"
    />
  </div>
</template>

<script>
import AllProjects from "@/components/AllProjects.vue";
import JsonProjects from "@/projects.json";
export default {
  name: "Projects",
  components: {
    AllProjects,
  },
  data: function () {
    return {
      projects: JsonProjects,
    };
  },
};
</script>

And the projects.json file:

[
  {
    "id":0,
    "title":"Blog Website",
    "image":"blog.png",
    "desc":"Description Of The Project"
  },
  {
    "id":1,
    "title":"Social Media Website",
    "image":"social-media.png",
    "desc":"Description Of The Project"
  },
  {
    "id":2,
    "title":"Online Courses Website",
    "image":"online-courses.png",
    "desc":"Description Of The Project"
  }
]

So where is my mistake?

The issue is in your image path - replace the '@' with the full path to your image, as it can not be resolved correctly:

:img = "`src/assets/${project.image}`"

The '@' char is a 'resolve alliance' used with webpack - from the webpack doc:

Create aliases to import or require certain modules more easily

You can try to bind your path to the dom like so: {{ @/assets/ }} and see it is not resolved to 'src', as it meant for modules importing and not to use inside the template. You can find more details about the 'resolve alliance' in another issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM