Vue + TS封装全局分页组件

素颜马尾好姑娘i 2023-10-13 05:29 78阅读 0赞

在Vue3项目中,我们常常会用到分页组件。为了方便复用和统一样式,我们可以封装一个全局的分页组件。

实现思路

  1. 定义一个Pagination组件,包含分页逻辑和样式。
  2. 在全局注册Pagination组件。
  3. 在需要使用分页组件的地方引入并使用。

代码实现

Pagination组件

  1. <template>
  2. <div class="pagination">
  3. <button :disabled="page === 1" @click="pageChange(page - 1)">上一页</button>
  4. <span v-for="index in totalPage" :key="index" :class="{active: index === page}" @click="pageChange(index)">{
  5. {
  6. index}}</span>
  7. <button :disabled="page === totalPage" @click="pageChange(page + 1)">下一页</button>
  8. </div>
  9. </template>
  10. <script lang="ts">
  11. import {
  12. defineComponent } from 'vue'
  13. export default defineComponent({
  14. name: 'Pagination',
  15. props: {
  16. total: {
  17. type: Number,
  18. required: true
  19. },
  20. pageSize: {
  21. type: Number,
  22. default: 10
  23. },
  24. currentPage: {
  25. type: Number,
  26. default: 1
  27. }
  28. },
  29. computed: {
  30. totalPage() {
  31. return Math.ceil(this.total / this.pageSize)
  32. },
  33. page() {
  34. return this.currentPage
  35. }
  36. },
  37. methods: {
  38. pageChange(page: number) {
  39. if (page < 1 || page > this.totalPage) {
  40. return
  41. }
  42. this.$emit('page-change', page)
  43. }
  44. }
  45. })
  46. </script>
  47. <style scoped>
  48. .pagination {
  49. display: flex;
  50. justify-content: center;
  51. align-items: center;
  52. button, span {
  53. margin: 0 5px;
  54. padding: 5px 10px;
  55. border-radius: 5px;
  56. cursor: pointer;
  57. }
  58. button:disabled, span.disabled {
  59. color: #999;
  60. cursor: not-allowed;
  61. }
  62. span.active {
  63. background-color: #1890ff;
  64. color: #fff;
  65. }
  66. }
  67. </style>

全局注册

  1. import {
  2. createApp } from 'vue'
  3. import Pagination from './components/Pagination.vue'
  4. const app = createApp(App)
  5. app.component('Pagination', Pagination)
  6. app.mount('#app')

使用

  1. <template>
  2. <div>
  3. <table>
  4. <!-- 表格内容 -->
  5. </table>
  6. <Pagination :total="total" :current-page="currentPage" @page-change="handlePageChange" />
  7. </div>
  8. </template>
  9. <script lang="ts">
  10. import {
  11. defineComponent, ref } from 'vue'
  12. export default defineComponent({
  13. name: 'MyComponent',
  14. setup() {
  15. const total = ref(50)
  16. const currentPage = ref(1)
  17. const handlePageChange = (page: number) => {
  18. currentPage.value = page
  19. // 发起请求获取指定页数据
  20. }
  21. return {
  22. total,
  23. currentPage,
  24. handlePageChange
  25. }
  26. }
  27. })
  28. </script>

总结

通过以上步骤,我们成功地封装了一个全局的分页组件。在需要使用的地方,只需要引入并传入必要的参数即可。

发表评论

表情:
评论列表 (有 0 条评论,78人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Vue + TS封装全局搜索组件

    本文介绍了如何使用Vue和TypeScript封装一个全局搜索组件。该组件可以方便地在Vue项目中使用,帮助用户快速定位所需信息。 组件功能 该全局搜索组件具有以下功能