Vue + TS封装全局分页组件

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

实现思路

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

代码实现

Pagination组件

<template>
  <div class="pagination">
    <button :disabled="page === 1" @click="pageChange(page - 1)">上一页</button>
    <span v-for="index in totalPage" :key="index" :class="{active: index === page}" @click="pageChange(index)">{{index}}</span>
    <button :disabled="page === totalPage" @click="pageChange(page + 1)">下一页</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'Pagination',
  props: {
    total: {
      type: Number,
      required: true
    },
    pageSize: {
      type: Number,
      default: 10
    },
    currentPage: {
      type: Number,
      default: 1
    }
  },
  computed: {
    totalPage() {
      return Math.ceil(this.total / this.pageSize)
    },
    page() {
      return this.currentPage
    }
  },
  methods: {
    pageChange(page: number) {
      if (page < 1 || page > this.totalPage) {
        return
      }
      this.$emit('page-change', page)
    }
  }
})
</script>

<style scoped>
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  button, span {
    margin: 0 5px;
    padding: 5px 10px;
    border-radius: 5px;
    cursor: pointer;
  }
  button:disabled, span.disabled {
    color: #999;
    cursor: not-allowed;
  }
  span.active {
    background-color: #1890ff;
    color: #fff;
  }
}
</style>

全局注册

import { createApp } from 'vue'
import Pagination from './components/Pagination.vue'

const app = createApp(App)

app.component('Pagination', Pagination)

app.mount('#app')

使用

<template>
  <div>
    <table>
      <!-- 表格内容 -->
    </table>
    <Pagination :total="total" :current-page="currentPage" @page-change="handlePageChange" />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'

export default defineComponent({
  name: 'MyComponent',
  setup() {
    const total = ref(50)
    const currentPage = ref(1)

    const handlePageChange = (page: number) => {
      currentPage.value = page
      // 发起请求获取指定页数据
    }

    return {
      total,
      currentPage,
      handlePageChange
    }
  }
})
</script>

总结

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值