vue实现ajax数据分页
Vue 实现 AJAX 数据分页的方法
使用 axios 发送 AJAX 请求
安装 axios 并导入到 Vue 组件中:
npm install axios
在组件中引入 axios:
import axios from 'axios';
发送分页请求示例:
methods: {
fetchData(page = 1) {
axios.get('/api/data', {
params: {
page: page,
per_page: 10
}
})
.then(response => {
this.items = response.data.data;
this.total = response.data.total;
})
.catch(error => {
console.error(error);
});
}
}
分页组件实现
在模板中添加分页控件:

<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
<div class="pagination">
<button
@click="fetchData(currentPage - 1)"
:disabled="currentPage === 1"
>
上一页
</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button
@click="fetchData(currentPage + 1)"
:disabled="currentPage === totalPages"
>
下一页
</button>
</div>
</div>
</template>
计算属性处理分页逻辑
添加计算属性计算总页数:
computed: {
totalPages() {
return Math.ceil(this.total / this.perPage);
}
},
data() {
return {
items: [],
total: 0,
currentPage: 1,
perPage: 10
};
}
服务器端分页处理
Node.js Express 示例:

app.get('/api/data', (req, res) => {
const page = parseInt(req.query.page) || 1;
const perPage = parseInt(req.query.per_page) || 10;
const offset = (page - 1) * perPage;
// 假设使用 Sequelize
Model.findAndCountAll({
limit: perPage,
offset: offset
})
.then(result => {
res.json({
data: result.rows,
total: result.count
});
});
});
优化用户体验
添加加载状态提示:
data() {
return {
isLoading: false
};
},
methods: {
fetchData(page = 1) {
this.isLoading = true;
axios.get('/api/data', {
params: {
page: page,
per_page: 10
}
})
.then(response => {
this.items = response.data.data;
this.total = response.data.total;
this.currentPage = page;
})
.finally(() => {
this.isLoading = false;
});
}
}
模板中添加加载状态:
<div v-if="isLoading">加载中...</div>
分页参数持久化
使用 Vue Router 保持分页状态:
watch: {
currentPage(newVal) {
this.$router.push({
query: {
...this.$route.query,
page: newVal
}
});
}
},
created() {
const page = parseInt(this.$route.query.page) || 1;
this.fetchData(page);
}






