Vue + TS はグローバル ページング コンポーネントをカプセル化します

Vue3 プロジェクトでは、ページネーション コンポーネントをよく使用します。スタイルの再利用と統一を容易にするために、グローバル ページング コンポーネントをカプセル化できます。

実装のアイデア

  1. ページング ロジックとスタイルを含むページネーション コンポーネントを定義します。
  2. ページネーション コンポーネントをグローバルに登録します。
  3. ページネーション コンポーネントが必要な場合に導入して使用します。

コード

ページネーションコンポーネント

<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