返回
Vue 项目之旅:用 vue 开发项目 - 第七天
前端
2024-02-04 08:00:09
走进第七天:文章详情功能的开发
各位朋友们,欢迎来到黑马头条项目的第七天旅程。今天,我们将一起深入探索 Vue.js 的奥妙,着重学习如何创建文章详情页面、配置路由以及进行测试。让我们开始吧!
1. 创建文章详情页面
首先,我们需要在 views
文件夹下创建 article
文件夹,并在其中新建 article.vue
文件。
在 article.vue
文件中,我们将编写以下代码:
<template>
<div>
<h1>{{ article.title }}</h1>
<p>{{ article.content }}</p>
</div>
</template>
<script>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
export default {
setup() {
const article = ref(null);
const router = useRouter();
const id = router.params.id;
// 请求文章详情数据
fetch(`/api/articles/${id}`)
.then(res => res.json())
.then(data => {
article.value = data;
});
return {
article
};
}
};
</script>
2. 配置路由
接着,我们需要在 router/index.js
文件中配置文章详情页面的路由:
import { createRouter, createWebHistory } from 'vue-router';
import Article from '../views/article/article.vue';
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/article/:id',
component: Article
}
]
});
export default router;
3. 测试效果
现在,我们可以通过运行项目来测试文章详情页面的效果了。
npm run serve
访问 http://localhost:8080/article/1
,您应该可以看到文章详情页面,其中包含文章的标题和内容。
4. 文章详情-路由跳转
最后,我们需要在其他页面添加跳转到文章详情页面的链接。
<a href="/article/1">文章详情</a>
点击这个链接,您应该可以顺利跳转到文章详情页面。
总结
通过今天的学习,我们已经掌握了如何使用 Vue.js 创建文章详情页面、配置路由以及进行测试。这些技能对于构建一个完整的 Vue 项目至关重要。希望您能继续关注我们的系列文章,在未来的旅程中,我们将继续探索 Vue.js 的更多奥秘。
课后作业
- 尝试在文章详情页面中添加评论功能。
- 尝试使用 Vuex 来管理文章详情页面的状态。
- 尝试使用第三方库来实现文章详情页面的富文本编辑器功能。