Vue.js应用帖子详情页不显示图片、标题、正文内容
问题修复方案
你遇到的问题是两个写法错误导致的,改完即可正常显示:
- 图片路径拼接错误
首页加载图片正常是因为你写的路径是/${post.image},开头带了站点根路径的斜杠;详情页的图片src少了这个开头的斜杠,浏览器会按当前详情页的相对路径找图片,肯定找不到。把详情页的<v-img>的src属性改成和首页一致的:src="/${post.image}"即可。 - 接口返回数据取值错误(这是标题、正文不显示的核心原因)
你封装的getAllPost方法内部应该已经做了响应解包——常规axios类请求返回的响应对象,实际业务数据都存在response.data字段里,getAllPost已经把这层data取出来返回给你了,所以首页赋值直接用没问题。但getPostByID方法你应该没做这个解包处理,直接把整个HTTP响应对象赋值给了this.post,这个对象里根本没有title、content、image这些帖子字段,模板自然渲染不出内容。
你可以先在const response = await API.getPostByID(...)这行下面加一句console.log(response),打开浏览器控制台看输出,就能看到你要的帖子数据是存在response的data属性里的,把赋值代码改成this.post = response.data就对了。 - 新手可选优化(避免控制台报错)
你现在data里post的初始值是空对象,页面第一次渲染时接口请求还没返回,模板访问post.title、post.content这些属性会触发undefined警告。你可以给外层的v-card加个判断v-if="post._id",等帖子数据加载完成后再渲染卡片内容,就不会有警告了。
修正后的详情页核心代码参考
<template> <v-container> <v-row no-gutters> <v-col sm="10" class="pa-4 mx-auto"> <!-- 加v-if等数据加载完再渲染 --> <v-card class="pa-2" v-if="post._id"> <!-- 补全图片路径的开头斜杠 --> <v-img :src="`/${post.image}`"></v-img> <v-card-actions class="pb-0"> <v-row class="mt-1 mx-1"> <v-col sm="2"> <v-btn small outlined color="primary">{{ post.category }}</v-btn> </v-col> <v-col sm="10" class="d-flex justify-end"> <v-btn color="success" text :to="{ name: 'edit-post', params: { id: post._id } }">Edit</v-btn> <v-btn color="red" text @click="deletePost(post._id)">Delete</v-btn> </v-col> </v-row> </v-card-actions> <v-card-subtitle class="headline"> <h3>{{ post.title }}</h3> </v-card-subtitle> <v-card-text class="grey--text"> <p>{{ post.content }}</p> <p>{{ post.created }}</p> </v-card-text> </v-card> </v-col> </v-row> </v-container> </template> <script> import API from '../api'; export default { data() { return { post: {}, }; }, async created(){ const response = await API.getPostByID(this.$route.params.id); // 如果控制台打印发现response本身就是帖子对象,就去掉.data,以实际打印结果为准 this.post = response.data || response; }, methods: { async deletePost(id) { const response = await API.deletePost(id); this.$router.push({ name: 'Home', params: { message: response.message } }); }, }, } </script>
内容的提问来源于stack exchange,提问作者Mario Moreno
相关产品推荐
相关产品推荐

