首页 > 解决方案 > 资产文件夹中的图像未使用 Vue Js 显示

问题描述

我尝试在这里查看不同的答案,但无法解决我的问题。我有一个带有一些数据的 Json 服务器:

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"
        },
        ]
    }

我希望我的组件在 v-for 中渲染“照片”上的图像,因为我不想每次添加新图像时都进行硬编码。这就是我的 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>

我已经测试了添加在线图像而不是我的资产中的图像,并且工作得非常好,所以我不确定为什么当我尝试从资产加载图像时不起作用。

这是它的显示方式

在此处输入图像描述

标签: vue.js

解决方案


看看这个(路径导入)这个(公共路径)

如果您想动态加载图像(在您的情况下使用{{post.photo}}),您必须将图像移动到您的/path/to/project/public/文件夹中。然后,您可以通过以下方式构建您的 src-url:

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

当您的公共路径不同时,将 替换'/'process.env.BASE_URL


推荐阅读