VUE3(二十三)自定义分页组件Pagination

刚开始使用vue3写博客的时候,其相关配套的UI库并没有正式发布,但是我还要用,所以这里我自定义了一个分页组件:最后效果如下图所示:

在这里插入图片描述

上代码:

Pagination.vue

<template>
  <!-- 自定义分页组件 -->
  <div class="page-bar">
    <ul>
      <li class="first">
        <!-- <span>共{{dataNum}}条记录 第 {{cur}} / {{all}} 页</span> -->
        <span>共{{ dataNum }}条记录 </span>
      </li>
      <li v-if="cur > 1" class="prev-next">
        <!-- 点击上一页 -->
        <a v-on:click="cur--, pageClick()"> prev </a>
      </li>
      <li v-if="cur == 1" class="prev-next">
        <!-- 点击第一页时显示 -->
        <a class="banclick"> prev </a>
      </li>
      <li
        class="li_a"
        v-for="index in indexs"
        v-bind:class="{ active: cur == index }"
      >
        <!-- 页码 -->
        <a v-on:click="btnClick(index)"> {{ index }}</a>
      </li>
      <li v-if="cur != all" class="prev-next">
        <!-- 点击下一页 -->
        <a v-on:click="cur++, pageClick()"> next </a>
      </li>
      <li v-if="cur == all" class="prev-next">
        <!-- 点击最后一页时显示 -->
        <a class="banclick"> next </a>
      </li>
 
      <li class="last_li">
        <!-- 共有多少页 -->
        跳至<input type="text" class="page-input" @blur.prevent="changePage()" v-model="jumpPage"></li>
 
      <li class="last_li">
        <!-- 共有多少页 -->
        <span
          ><i>{{ all }}</i
          ></span
        >
      </li>
    </ul>
  </div>
</template>
<script>
// 引入js文件
import Pagination from "/@/assets/js/components/pc/Pagination";
// 使用js对象
export default {
  ...Pagination,
};
</script>
<style lang="scss" scoped>
@import "../../assets/css/components/pc/Pagination.scss";
</style>

Pagination.ts

import {
  PropType,
  ref,
  watch,
  computed,
  reactive,
  toRefs,
  inject,
  provide,
  onMounted
} from "vue";
// 引入公共js文件
import utils from "/@/assets/js/public/function";
// 定义返回的类型
interface dataRef {
  btnClick: (val:number) => void;
  pageClick: () => void;
  changePage: () => void;
}
export default {
  name: "Pagination",
  props: {
    // 总页数
    'dataAll': {
      type: Number,
      default: 100,
      required: true
    },
    // 当前页数
    'dataCur': {
      type: Number,
      default: 1,
      required: true
    },
    // 页面条数
    'datanum': {
      type: Number,
      default: 7
    },
    // 数据总量
    'dataDatanum': {
      type: Number,
      default: 456
    },
  },
  // VUE3语法 setup函数
  // setup官方文档:https://www.vue3js.cn/docs/zh/guide/composition-api-setup.html#参数
  setup(props: any, content:any): dataRef 
  {
    /**
     * @name: 声明data
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-01-10 
     */
    const data:any = reactive({
      all: props.dataAll, //总页数
      cur: Number(props.dataCur),//当前页码
      num: props.datanum, //一页显示的数量  奇数
      dataNum: props.dataDatanum,//数据的数量
      jumpPage:0,// 跳转页码
      indexs:computed(()=>{
        var left = 1;
        var right = data.all;
        var ar = [];
        if (data.all >= data.num) 
        {
          if (data.cur > 3 && data.cur < data.all - 2) 
          {
            left = data.cur - (data.num - 1) / 2;
            right = Number(data.cur) + Number((data.num - 1) / 2);
          } 
          else 
          {
            if (data.cur <= 3) 
            {
              left = 1
              right = data.num
            } 
            else 
            {
              right = data.all
              left = data.all - (data.num - 1);
            }
          }
        }
        while (left <= right) 
        {
          ar.push(left)
          left++
        }
        return ar
      })
    });
 
    /**
     * @name: 页码点击事件
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-01-11 
     */
    const btnClick = (val:Number) => { 
      if (val != data.cur) 
      {
        data.cur = val
        content.emit('changePage', data.cur);
      }
    };
    /**
     * @name: 点击上一页下一页
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-01-11 
     */
    const pageClick = () => {
      //父组件通过changePage方法来接受当前的页码
      //这里是点击下一页执行函数
      content.emit('changePage', data.cur)
    }
 
    /**
     * @name: 跳至 xxx 页
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-01-13 
     */
    const changePage = () => {
      if (data.jumpPage > data.all || data.jumpPage < 1 || isNaN(data.jumpPage) )
      {
        utils.alertMsg(2000,"参数错误!");return;
      }
      content.emit('changePage', Number(data.jumpPage))
    }
 
    /**
     * @name: 将data绑定值dataRef
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-01-10 
     */
    const dataRef = toRefs(data);
    return {
      btnClick,
      pageClick,
      changePage,
      ...dataRef
    }
  },
}

Pagination.scss

 .page-bar {
   text-align: center;
   width: 100%;
   height: 36px;
   margin: 0 auto;
   position: relative;
 }
 
 .page-bar ul {
   min-width: 800px;
   display: block;
   overflow: hidden;
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%,-50%);
   }
 
.page-bar li {
   display: block;
    border: 1px solid #ddd;
   width: 36px;
   height: 36px;
   border-radius: 4px;
   list-style: none;
   overflow: hidden;
   position: relative;
   float: left;
   margin-left: 8px;
}
.page-bar .first{
   display: block;
  //  width: 170px;
   width: 100px;
   height: 36px;
   font-size: 14px;
   line-height: 36px;
   text-align: center;
}
.page-bar .last_li{
   width: 100px;
   height: 36px;
   border: 1px solid #ddd;
   line-height: 34px;
}
.page-bar .last_li span{
    width: 100%;
   height: 100%;
   line-height: 36px;
   text-align: center;
   float: left;
}
.page-bar li:first-child {
   margin-left: 0px
}
 
.page-bar a {
   width: 34px;
   height: 34px;
   text-decoration: none;
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%,-50%);
   /*margin-left: -1px;*/
   line-height:  34px;
   color: #333;
   cursor: pointer
}
 
.page-bar .li_a a:hover {
   background-color: #eee;
   border: 1px solid #40A9FF;
   color: #40A9FF;
}
 
.page-bar a.banclick {
   cursor: not-allowed;
}
 
.page-bar .active a {
   color: #fff;
   cursor: default;
   background-color: #1890FF;
   border-color: #1890FF;
}
 
.page-bar i {
   font-style: normal;
   color: #d44950;
   margin: 0px 4px;
   font-size: 14px;
}
.page-bar .prev-next{
  width:50px;
}
 
.page-bar input{  
   background:none;  
   outline:none;  
  border:1px solid #ccc;
  
}
.page-bar .page-input{
  width: 30px;
  height: 25px;
  padding-left: 6px;
}

父组件调用:

Index.ts

import {
    PropType,
    ref,
    watch,
    reactive,
    toRefs,
    getCurrentInstance,
    provide,
    inject,
    onBeforeMount,// 在组件挂载之前执行的函数
    onMounted,
    onBeforeUpdate,// 在组件修改之前执行的函数
    onUpdated,
    onBeforeUnmount,// 在组件卸载之前执行的函数
    onUnmounted,
    nextTick
} from "vue";
// 引入axios钩子
import axios from "/@/hooks/axios.ts";
// 引入路由
import { useRouter, useRoute } from "vue-router";
 
// 引入各个自定义组件(懒加载)
// const HelloWorld = () => import("/@/components/HelloWorld.v
import Pagination from "/@/components/pc/Pagination.vue";
 
export default {
    name: "index",
    components: {
        Pagination,
    },
    // VUE3 语法 第一个执行的钩子函数
    // setup官方文档 :https://www.vue3js.cn/docs/zh/guide/composition-api-setup.html#参数
    // setup(props: any, content: any) {
    setup(props: any, content: any) {
        const router = useRouter();
        const route = useRoute()
        //获取上下文实例,ctx=vue2的this
        // const { ctx,proxy } = getCurrentInstance();
        /**
         * @name: 声明data
         * @author: camellia
         * @email: guanchao_gc@qq.com
         * @date: 2021-01-10 
         */
        const data = reactive({
            // 文章列表
            articleList:[],
            // 数据页数
            articlePage:0,
            // 当前页
            currentPage: route.query.page ? route.query.page : 1,
            // 分页显示页码数
            dataNum:7,
            // 查询条件
            search:'search',
            // 数据总条数
            dataDatanum:'',
        });
 
        /**
         * @name: 分页子组件传递值方法
         * @author: camellia
         * @email: guanchao_gc@qq.com
         * @date: 2021-01-11 
         * @param:  param   Number  子组件传递来的页码
         */
        const changePage = (param: number) => {
            data.currentPage = param;
            getData('page');
            router.push(
            { 
                path: '/pc/index', 
                query: { 
                    page: JSON.stringify(data.currentPage) 
                }
            });
        }
        // 初始调用
        getData();
 
        /**
         * @name: 将data绑定值dataRef
         * @author: camellia
         * @email: guanchao_gc@qq.com
         * @date: 2021-01-10 
         */
        const dataRef = toRefs(data);
        return {
            getData,
            changePage,
            ...dataRef
        }
    },//*/
};

代码中有注释,我这里就不做赘述了。

当然,你还可以扩展其他功能。

有好的建议,请在下方输入你的评论。
欢迎访问个人博客
https://guanchao.site

欢迎访问小程序:

在这里插入图片描述

以下是一个简单的自定义分页组件的示例,使用Vue2实现: ``` <template> <div> <ul class="pagination"> <li :class="{ 'disabled': currentPage === 1 }"> <a href="#" @click.prevent="prevPage"> Previous </a> </li> <li v-for="page in pages" :class="{ 'active': page === currentPage }"> <a href="#" @click.prevent="changePage(page)">{{ page }}</a> </li> <li :class="{ 'disabled': currentPage === totalPages }"> <a href="#" @click.prevent="nextPage"> Next </a> </li> </ul> </div> </template> <script> export default { props: { currentPage: { type: Number, required: true, }, totalPages: { type: Number, required: true, }, maxPagesToShow: { type: Number, default: 5, }, }, computed: { pages() { let pages = []; let startPage = 1; let endPage = this.totalPages; if (this.maxPagesToShow < this.totalPages) { let middle = Math.ceil(this.maxPagesToShow / 2); startPage = Math.max(this.currentPage - middle + 1, 1); endPage = startPage + this.maxPagesToShow - 1; if (endPage > this.totalPages) { endPage = this.totalPages; startPage = endPage - this.maxPagesToShow + 1; } } for (let i = startPage; i <= endPage; i++) { pages.push(i); } return pages; }, }, methods: { changePage(page) { this.$emit('change-page', page); }, prevPage() { if (this.currentPage > 1) { this.changePage(this.currentPage - 1); } }, nextPage() { if (this.currentPage < this.totalPages) { this.changePage(this.currentPage + 1); } }, }, }; </script> <style> .pagination { display: inline-block; } .pagination li { display: inline; padding: 5px 10px; } .pagination li.disabled a, .pagination li.active a { pointer-events: none; color: #777; cursor: default; } </style> ``` 在父组件中引入自定义分页组件并使用,示例代码如下: ``` <template> <div> <table> <!-- 表格内容省略 --> </table> <custom-pagination :current-page="currentPage" :total-pages="totalPages" @change-page="handlePageChange" /> </div> </template> <script> import CustomPagination from './CustomPagination.vue'; export default { components: { CustomPagination, }, data() { return { currentPage: 1, totalPages: 10, }; }, methods: { handlePageChange(page) { this.currentPage = page; // 切换页面数据的方法 }, }, }; </script> ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值