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>

总结

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

猜你喜欢

转载自blog.csdn.net/qq_27244301/article/details/131454310