vue实现商品分页
Vue 实现商品分页的方法
基础分页实现
安装必要的依赖(如axios用于请求数据)
npm install axios
创建分页组件模板
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
数据逻辑处理
设置初始数据状态
data() {
return {
items: [],
currentPage: 1,
itemsPerPage: 10,
totalItems: 0
}
}
计算总页数
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.itemsPerPage)
}
}
API请求方法
实现获取分页数据的方法

methods: {
async fetchItems() {
try {
const response = await axios.get('/api/products', {
params: {
page: this.currentPage,
limit: this.itemsPerPage
}
})
this.items = response.data.items
this.totalItems = response.data.total
} catch (error) {
console.error('获取数据失败:', error)
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
this.fetchItems()
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
this.fetchItems()
}
}
}
生命周期钩子
在组件挂载时加载初始数据
mounted() {
this.fetchItems()
}
样式优化
添加基础分页样式
.pagination {
margin-top: 20px;
display: flex;
justify-content: center;
align-items: center;
gap: 15px;
}
button {
padding: 5px 10px;
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
高级分页功能
实现页码跳转功能

<input
type="number"
v-model.number="inputPage"
min="1"
:max="totalPages"
@keyup.enter="goToPage"
>
<button @click="goToPage">跳转</button>
添加对应方法
data() {
return {
inputPage: 1
}
},
methods: {
goToPage() {
const page = Math.max(1, Math.min(this.inputPage, this.totalPages))
if (page !== this.currentPage) {
this.currentPage = page
this.fetchItems()
}
}
}
性能优化
添加加载状态
data() {
return {
isLoading: false
}
},
methods: {
async fetchItems() {
this.isLoading = true
try {
// ...原有请求代码
} finally {
this.isLoading = false
}
}
}
在模板中添加加载指示器
<div v-if="isLoading">加载中...</div>
服务器端分页
确保后端API支持分页参数
// 示例Node.js后端处理
router.get('/api/products', async (req, res) => {
const page = parseInt(req.query.page) || 1
const limit = parseInt(req.query.limit) || 10
const skip = (page - 1) * limit
const items = await Product.find().skip(skip).limit(limit)
const total = await Product.countDocuments()
res.json({ items, total })
})






