前端分页及搜索过滤的简单实现
一般分页和搜索过滤都是后端来完成,,但是有时临时加的需求,数据简单,后端改起来涉及到的地方比较多,比较麻烦就由前端来完成
<template>
<div>
<a-input-search
v-model="inputKey"
placeholder="姓名搜索"
style="width: 200px"
@search="onSearch"
/>
<div class="thead">
<span class="th">序号</span>
<span class="th">姓名</span>
<span class="th">年龄</span>
<span class="th">性别</span>
</div>
<div v-for="(item, index) in displayList" :key="index">
<span class="td">{{ (currentPage - 1) * pageSize + index + 1 }}</span>
<span class="td">{{ item.name }}</span>
<span class="td">{{ item.age }}</span>
<span class="td">{{ item.gender }}</span>
</div>
<a-pagination
:default-current="1"
v-model="currentPage"
:total="total"
@change="pageChange"
v-show="total"
/>
</div>
</template>
<script>
import tableList from "./tableData.js"; // 表格的数据来源
export default {
data() {
return {
// list: [],
currentPage: 1,
pageSize: 10,
displayList: [],
inputKey: "",
searchResult: [],
total: 0,
};
},
watch: {
displayList: {
handler: function() {
if (this.inputKey.trim()) {
this.total = this.searchResult.length;
} else {
this.total = tableList.length;
}
},
},
},
mounted() {
this.displayList = tableList.slice(0, 10);
},
methods: {
pageChange() {
if (!this.inputKey.trim()) {
this.displayList = tableList.slice(
(this.currentPage - 1) * this.pageSize,
this.currentPage * this.pageSize
);
} else {
this.displayList = this.searchResult.slice(
(this.currentPage - 1) * this.pageSize,
this.currentPage * this.pageSize
);
}
},
onSearch() {
this.currentPage = 1;
if (this.inputKey.trim()) {
this.searchResult = tableList.filter((item) =>
item.name.includes(this.inputKey)
);
this.displayList = this.searchResult.slice(
(this.currentPage - 1) * this.pageSize,
this.currentPage * this.pageSize
);
} else {
this.displayList = tableList.slice(
(this.currentPage - 1) * this.pageSize,
this.currentPage * this.pageSize
);
}
},
},
};
</script>
<style lang="less">
div .th,
.td {
display: inline-block;
padding: 10px;
width: 160px;
box-sizing: border-box;
}
.ant-input-affix-wrapper .ant-input-suffix {
right: 10px;
}
</style>
这只是一个简单的前端分页及搜索过滤功能实现,还有很多需要优化的地方