> 文章列表 > Ant Design Vue表格(Table)及分页(Pagination )使用

Ant Design Vue表格(Table)及分页(Pagination )使用

Ant Design Vue表格(Table)及分页(Pagination )使用

前言

最近在写一个新项目,UI框架用的是 Ant Design Vue,因为之前一直用的 Element UI,没有用过这个组件库,没想到二者区别这么大,因此踩了不少坑,其中就有 TablePagination,花了一会时间才弄明白,在此记录并分享一下此次经历。

注意:是 Vue3 项目。

一、Table 表格

Table 的使用相对比较简单,与 Element 不同的是,它不需要写很多的标签,主要通过数据来改变列表显示。

表格的列标题和数据分别用 columnsdata 两个数组来控制,命名随意。分别将其传给表格的 columnsdata-source对象即可。

注意:数组中的 key 值是有一定要求的,如 标题必须为 titlecolumnskeydata 中的值的名字等。具体的字段名称就要去看官方文档了,本文就不做赘述了。

<script setup lang='ts'>
import { ref } from 'vue';const columns = ref([{title: '标题',dataIndex: 'name',key: 'name',
},{title: '时间',dataIndex: 'date',key: 'date',
}])const data = ref([{key: 1,name: 'Ant Design Vue表格',year: '2023年',
}])
</script><template><a-table :columns="columns" :data-source="data" :pagination="pagination"></a-table>
</template>

Ant Design Vue表格(Table)及分页(Pagination )使用

上面只是正常的数据展示,但是有些时候我们需要做一些逻辑处理,比如按钮什么的,这种情况下就需要使用 <template></template>进行处理。

需要注意的是,这里需要两层<template></template>,外面一层是一个具名插槽,我们要处理的是 body ,因此需要加上 #bodyCell="{ column }"

.vue

<script setup lang='ts'>
import { ref } from 'vue';const columns = ref([{title: '考核名称',dataIndex: 'name',key: 'name',
}, {title: '考核名称',dataIndex: 'name',key: 'name',
}, {title: '考核名称',dataIndex: 'name',key: 'name',
}])const data = ref([{key: 1,name: '测试',
}])
</script><template><a-table :columns="columns" :data-source="data" :pagination="pagination"><template #bodyCell="{ column }"><template v-if="column.key === 'status'"><dsa-tag type="warn">已完成</dsa-tag></template><template v-else-if="column.key === 'operate'"><a class="button">编辑</a></template></template></a-table>
</template>

Ant Design Vue表格(Table)及分页(Pagination )使用

二、Pagination 分页

通过上面的代码我们可以发现,表格中并未使用分页组件,但是页码依然展示出来了,你可能会觉得这很方便,但实际上,这样的方式,会让很多功能都无法实现。因此,我们需要对分页进行定制处理。

Table 相同,分页同样是通过数据去控制,因为表格默认已经使用了分页,所以我们无需额外引入。但是需要在表格上添加 :pagination="pagination" ,指定控制分页的数据。
.vue

<script setup lang='ts'>
import { ref } from 'vue';const pagination = ref({current: 1,defaultPageSize: 10,total: 11,showTotal: () => `${11}`
})const columns = ref([{title: '考核名称',dataIndex: 'name',key: 'name',
}, {title: '考核名称',dataIndex: 'name',key: 'name',
}, {title: '考核名称',dataIndex: 'name',key: 'name',
}])const data = ref([{key: 1,name: '测试',
}])
</script><template><a-table :columns="columns" :data-source="data" :pagination="pagination"><template #bodyCell="{ column }"><template v-if="column.key === 'status'"><dsa-tag type="warn">已完成</dsa-tag></template><template v-else-if="column.key === 'operate'"><a class="button">编辑</a></template></template></a-table>
</template>

分页的配置项有很多,具体参考官方文档 Pagination 分页。

END