vue文章列表详情实现
Vue 文章列表与详情页实现
路由配置
在 router/index.js 中配置动态路由,实现列表到详页的跳转:
const routes = [
{
path: '/articles',
component: () => import('@/views/ArticleList.vue')
},
{
path: '/articles/:id',
component: () => import('@/views/ArticleDetail.vue'),
props: true
}
]
文章列表组件
使用 v-for 渲染列表数据,通过 router-link 实现跳转:

<template>
<div>
<div v-for="article in articles" :key="article.id">
<router-link :to="'/articles/' + article.id">
<h3>{{ article.title }}</h3>
</router-link>
<p>{{ article.summary }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
articles: [
{ id: 1, title: 'Vue入门', summary: 'Vue基础知识介绍' },
{ id: 2, title: 'Vue路由', summary: 'Vue Router使用指南' }
]
}
}
}
</script>
文章详情组件
通过路由参数 id 获取对应文章内容:
<template>
<div v-if="article">
<h2>{{ article.title }}</h2>
<div>{{ article.content }}</div>
</div>
</template>
<script>
export default {
props: ['id'],
data() {
return {
article: null
}
},
created() {
this.fetchArticle()
},
methods: {
fetchArticle() {
// 模拟API请求
const articles = [
{ id: 1, title: 'Vue入门', content: '这里是详细内容...' },
{ id: 2, title: 'Vue路由', content: '这里是详细内容...' }
]
this.article = articles.find(item => item.id === Number(this.id))
}
}
}
</script>
数据请求优化
使用 Axios 从后端 API 获取数据:

import axios from 'axios'
methods: {
async fetchArticles() {
try {
const res = await axios.get('/api/articles')
this.articles = res.data
} catch (error) {
console.error(error)
}
}
}
状态管理(可选)
对于大型应用,可使用 Vuex 管理文章状态:
// store/modules/articles.js
const actions = {
async fetchArticles({ commit }) {
const res = await axios.get('/api/articles')
commit('SET_ARTICLES', res.data)
}
}
样式优化
添加过渡效果提升用户体验:
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}






