RandomDeveloper
RandomDeveloper

Reputation: 873

Image from assets folder not displaying with Vue Js

I have tried looking at different answers here but could not resolve my problem. I have got a Json server with some data:

file.json
    {
      "post": [
        {
          "id": "1",
          "title": "Title",
          "description": "Este e um post para saberes mais clica aqui",
          "article": "Hoje este e um novo post etc e tal",
          "photo": "image-1.jpg"
        },
        ]
    }

I want my component to render the image on 'photo' in a v-for as I don't want to hard code every time I add a new one. This is what I have in my component.vue:

<template>
  <section>
    <h2 class="mt-32 flex justify-center text-3xl ">The Happy Algorithm</h2>
    <div class="grid grid-rows-4 grid-flow-col">
      <div class="ml-12 " v-for="(post, index) in posts" :key="index">
        <router-link :to="{ name: 'post', params: { id: post.id } }">
          <a href=""
            ><img
              class=" mt-8 pt-32 "
              :src="`../assets/${post.photo}`"
              :alt="post.title"
          /></a>
          <h2>{{ post.title }}</h2>
          <p class="text-justify text-sm pt-6">
            {{ post.description }}
          </p>
        </router-link>
      </div>
    </div>
  </section>
</template>
<script>
import { api } from "@/../services.js";

export default {
  name: "LatestPost",
  props: ["id"],
  data() {
    return {
      posts: [],
    };
  },
  methods: {
    getAllPosts() {
      this.posts = [];
      api.get(`/post`).then(response => {
        this.posts = response.data;
        console.log(this.posts);
      });
    },
  },
  created() {
    this.getAllPosts();
  },
};
</script>

I have tested adding an online image instead of the one I have in my assets and works absolutely fine so I am not sure why doesn't work when I try to load the image from assets.

This is how it displays

enter image description here

Upvotes: 1

Views: 2762

Answers (2)

Asuza
Asuza

Reputation: 38

You can also use the require function while trying to load the image

:src="require(`../assets/${post.photo}`)"

Upvotes: 0

Kodiak
Kodiak

Reputation: 532

Take a look at this (Path imports) and this one(public path)

If you want to load images dynamically (in your case with the {{post.photo}}) you have to move the images to your /path/to/project/public/ folder. You can build your src-url in the following way then:

<img class="mt-8-pt-32" :src="'/' + post.photo" :alt="post.title">

When your public path is different, replace the '/' with process.env.BASE_URL.

Upvotes: 3

Related Questions