打造专属的博客帝国:Node系列学习之博客前台精彩搭建
2024-01-13 11:40:14
Node系列学习之博客前台(三):搭建博客详情页,展现内容魅力
在上一篇文章中,我们搭建了博客主页和博客分类页,为我们的博客网站奠定了坚实的基础。现在,是时候深入挖掘,搭建博客详情页,让您的博客内容大放异彩。在这个过程中,您将了解如何使用Vue.js或React.js构建博客详情页,如何处理博客文章的发布时间,以及如何使用dayjs.js进行时间格式化。让我们开始吧!
一、构建博客详情页的骨架
- 搭建基本框架
首先,我们需要为博客详情页构建一个基本框架。您可以使用Vue.js或React.js来构建这个框架。如果您是Vue.js的爱好者,可以参考以下代码:
<template>
<div class="blog-detail-page">
<div class="blog-detail-header">
<h1>{{ article.title }}</h1>
<div class="blog-detail-info">
<span>{{ article.author }}</span>
<span>{{ article.publishDate }}</span>
</div>
</div>
<div class="blog-detail-content">
<div v-html="article.content"></div>
</div>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['article']),
},
}
</script>
<style>
.blog-detail-page {
padding: 20px;
}
.blog-detail-header {
margin-bottom: 20px;
}
.blog-detail-header h1 {
font-size: 24px;
font-weight: bold;
}
.blog-detail-info {
font-size: 14px;
color: #999;
}
.blog-detail-content {
font-size: 16px;
}
</style>
- 获取博客文章数据
接下来,我们需要获取博客文章的数据。您可以使用Vuex来管理博客文章的数据。在Vuex的store中,您可以定义一个名为“article”的状态,并通过Vuex的mapState函数将这个状态映射到博客详情页组件中。
export default {
computed: {
...mapState(['article']),
},
}
- 渲染博客文章数据
获取到博客文章的数据后,您就可以将其渲染到博客详情页上。在博客详情页组件中,您可以使用v-html指令将博客文章的内容渲染到页面上。
<div v-html="article.content"></div>
二、处理博客文章的发布时间
在博客详情页上,您需要显示博客文章的发布时间。您可以使用dayjs.js来对博客文章的发布时间进行格式化。
import dayjs from 'dayjs'
export default {
computed: {
...mapState(['article']),
publishDate() {
return dayjs(this.article.publishDate).format('YYYY-MM-DD')
},
},
}
三、联调博客详情页
现在,您已经搭建好了博客详情页,并且可以获取和渲染博客文章的数据。接下来,您需要将博客详情页与博客后端进行联调。您可以使用axios或fetch来发送HTTP请求,从博客后端获取博客文章的数据。
import axios from 'axios'
export default {
methods: {
async fetchArticle(id) {
const response = await axios.get(`/api/articles/${id}`)
this.$store.commit('setArticle', response.data)
},
},
}
四、总结
在本文中,我们搭建了博客详情页,并实现了博客文章数据的获取和渲染。我们还使用dayjs.js对博客文章的发布时间进行了格式化。至此,我们的博客网站已经初具规模。在下一篇文章中,我们将继续完善博客网站,添加更多有趣的功能。敬请期待!