vue实现新闻列表
使用 Vue 实现新闻列表
数据准备
新闻列表通常需要从后端 API 获取数据,或使用本地模拟数据。以下是一个示例新闻数据格式:
const newsList = [
{
id: 1,
title: "Vue 3.0 正式发布",
content: "Vue 3.0 带来了更快的性能和更好的 TypeScript 支持",
date: "2023-01-01",
author: "Evan You"
},
{
id: 2,
title: "Composition API 详解",
content: "新的 Composition API 提供了更灵活的代码组织方式",
date: "2023-01-02",
author: "Vue 团队"
}
]
组件结构
创建一个新闻列表组件 NewsList.vue:

<template>
<div class="news-list">
<div v-for="item in news" :key="item.id" class="news-item">
<h3>{{ item.title }}</h3>
<p>{{ item.content }}</p>
<div class="meta">
<span>{{ item.date }}</span>
<span>{{ item.author }}</span>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
news: []
}
},
mounted() {
this.fetchNews()
},
methods: {
async fetchNews() {
// 这里替换为实际的 API 调用
// const response = await axios.get('/api/news')
// this.news = response.data
// 临时使用模拟数据
this.news = [
{
id: 1,
title: "Vue 3.0 正式发布",
content: "Vue 3.0 带来了更快的性能和更好的 TypeScript 支持",
date: "2023-01-01",
author: "Evan You"
},
{
id: 2,
title: "Composition API 详解",
content: "新的 Composition API 提供了更灵活的代码组织方式",
date: "2023-01-02",
author: "Vue 团队"
}
]
}
}
}
</script>
<style scoped>
.news-list {
max-width: 800px;
margin: 0 auto;
}
.news-item {
margin-bottom: 20px;
padding: 15px;
border: 1px solid #eee;
border-radius: 4px;
}
.meta {
color: #666;
font-size: 0.8em;
margin-top: 10px;
}
.meta span {
margin-right: 10px;
}
</style>
使用 Composition API
如果需要使用 Vue 3 的 Composition API,可以这样改写:

<script setup>
import { ref, onMounted } from 'vue'
const news = ref([])
const fetchNews = async () => {
// 实际项目中替换为 API 调用
news.value = [
{
id: 1,
title: "Vue 3.0 正式发布",
content: "Vue 3.0 带来了更快的性能和更好的 TypeScript 支持",
date: "2023-01-01",
author: "Evan You"
}
]
}
onMounted(() => {
fetchNews()
})
</script>
分页功能
实现基本的分页功能可以添加以下代码:
<template>
<!-- 原有代码不变 -->
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="nextPage">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
news: [],
currentPage: 1,
totalPages: 1
}
},
methods: {
async fetchNews() {
// 模拟分页数据
const allNews = [...]
const perPage = 10
this.totalPages = Math.ceil(allNews.length / perPage)
this.news = allNews.slice(
(this.currentPage - 1) * perPage,
this.currentPage * perPage
)
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
this.fetchNews()
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
this.fetchNews()
}
}
}
}
</script>
路由跳转
为新闻项添加详情页跳转:
<template>
<div class="news-list">
<div
v-for="item in news"
:key="item.id"
class="news-item"
@click="goToDetail(item.id)"
>
<!-- 原有内容 -->
</div>
</div>
</template>
<script>
export default {
methods: {
goToDetail(id) {
this.$router.push(`/news/${id}`)
}
}
}
</script>
以上代码提供了实现新闻列表的基本框架,可以根据实际需求进行调整和扩展。






