我尝试在这里查看其他答案,但无法解决我的问题。 我有一个带有一些数据的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>
我已经测试过添加一个在线图像,而不是添加一个我的资产中的图像,并且可以正常工作,所以我不确定为什么当我尝试从资产中加载图像时为什么不起作用。
这是它的显示方式
答案 0 :(得分:1)
看看this (Path imports)和this one(public path)
如果要动态加载图像(在使用{{post.photo}}
的情况下),则必须将图像移动到/path/to/project/public/
文件夹中。您可以按照以下方式构建src-url:
<img class="mt-8-pt-32" :src="'/' + post.photo" :alt="post.title">
当您的公共路径不同时,将'/'
替换为process.env.BASE_URL
。
答案 1 :(得分:0)
尝试为
<img
class=" mt-8 pt-32 "
:src="require(`../assets/${post.photo}`)"
:alt="post.title"/>