使用 Vue 3 实现一个简单的博客架构,包含文章列表和文章详情
随着现代 web 开发的不断推进,Vue 3 作为一个渐进式框架,因其简洁易学、响应式强大而广受欢迎。在这篇博客中,我们将使用 Vue 3 实现一个简单的博客架构,包含文章列表和文章详情页面。我们将借助 Vue 3 的 setup 语法糖,使得代码更加简洁,易于维护。
项目结构
在开始之前,我们需要确定项目的基本结构。为了保持简洁,我们将主要有以下几个组件:
App.vue
— 应用的主组件ArticleList.vue
— 文章列表组件ArticleDetail.vue
— 文章详情组件
安装 Vue 3
首先,你需要创建一个新的 Vue 3 项目。你可以使用 Vue CLI 来快速创建项目:
npm install -g @vue/cli
vue create simple-blog
cd simple-blog
选择 Vue 3 配置,安装完成后进入项目目录。
创建组件
1. App.vue
在根组件 App.vue
中,我们将设置基本路由结构。使用 Vue Router 进行页面的切换。
<template>
<div id="app">
<nav>
<router-link to="/">文章列表</router-link>
</nav>
<router-view />
</div>
</template>
<script setup>
import { defineComponent } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import ArticleList from './components/ArticleList.vue'
import ArticleDetail from './components/ArticleDetail.vue'
const routes = [
{ path: '/', component: ArticleList },
{ path: '/article/:id', component: ArticleDetail },
]
const router = createRouter({
history: createWebHistory(),
routes,
})
export default defineComponent({
setup() {
return { router }
}
})
</script>
<style>
nav {
padding: 1rem;
background-color: #f8f9fa;
}
nav a {
margin: 0 1rem;
text-decoration: none;
}
</style>
2. ArticleList.vue
在 ArticleList.vue
中,我们将展示一个简单的文章列表。通过使用 ref
和 computed
来管理和显示文章数据。
<template>
<div>
<h1>文章列表</h1>
<ul>
<li v-for="article in articles" :key="article.id">
<router-link :to="`/article/${article.id}`">{{ article.title }}</router-link>
</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue'
const articles = ref([
{ id: 1, title: '第一篇文章' },
{ id: 2, title: '第二篇文章' },
{ id: 3, title: '第三篇文章' },
])
</script>
<style>
ul {
list-style-type: none;
padding: 0;
}
</style>
3. ArticleDetail.vue
在 ArticleDetail.vue
中,我们将根据文章 ID 显示相应的文章详细信息。我们将使用 useRoute
钩子来获取路由参数。
<template>
<div>
<h1>{{ article.title }}</h1>
<p>{{ article.content }}</p>
<router-link to="/">返回列表</router-link>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
const articles = [
{ id: 1, title: '第一篇文章', content: '这是第一篇文章的内容。' },
{ id: 2, title: '第二篇文章', content: '这是第二篇文章的内容。' },
{ id: 3, title: '第三篇文章', content: '这是第三篇文章的内容。' },
]
const route = useRoute()
const article = ref({})
onMounted(() => {
const articleId = parseInt(route.params.id)
article.value = articles.find(a => a.id === articleId) || {}
})
</script>
<style>
h1 {
margin-top: 20px;
}
</style>
路由配置
在上述代码中,我们在 App.vue
中创建了路由以管理不同的视图。在实际的应用中,你可能需要安装 Vue Router。你可以运行 npm install vue-router@4
来安装它。
启动项目
现在,经过以上步骤,我们已经完成了简单的博客架构。接下来,启动项目:
npm run serve
在浏览器中打开 http://localhost:8080
,你将看到文章列表,点击文章标题可以跳转到文章详情页。
总结
通过使用 Vue 3 的 setup 语法糖,我们能够快速构建一个简单的博客架构。在这个例子中,我们展示了如何使用 Vue Router 管理路由,以及如何使用响应式数据展示文章列表和详情。
当然,以上的结构非常基础,随着你对 Vue 的深入了解,你可以添加更多的功能,比如评论系统、文章创建、删除等操作。