TS + vue3 + element-plus 分页组件封装

记录下封装分页组件的小坑,由于开始子组件使用的:current-page来绑定,切换页码的时候页码视图没有变化,导致以为是子组件无法监听到父组件的数据变化导致的,后面查看文档使用v-model="current_page"视图就可以变化了

父组件
 <div class="pagination">
        <pagination
          :current-page="changePage.currentPage"
          :page-sizes="[5, 15, 20, 25, 30, 35]"
          :total="userStore.userList.total"
          @current-change="handleCurrentChange"
        />
<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";

import { useUserList } from "@/store/userList";
import pagination from "@/components/pagination.vue";
const userStore = useUserList();
const changePage = reactive<pagination_type>({
  currentPage: 1,
  limit: 10,
});
onMounted(async () => {
  await userStore.getUserListApi(changePage);
});

const handleCurrentChange = async (val: number) => {
  changePage.currentPage = val;
  await userStore.getUserListApi(changePage);
};
</script>
子组件
<template>
  <div>
    <el-pagination
      background
      :layout="layout"
      v-model="current_page"
      :page-sizes="page_sizes"
      :total="total"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup lang="ts">
import { toRefs} from "vue"
type Props = {
  layout?: string;
  current_page?: number;
  page_sizes?: number[];
  total?: number;
};
const propData = withDefaults(defineProps<Props>(), {
  layout: "prev, pager, next",
  current_page: 1,
  page_sizes: () => [5, 15, 20, 25, 30, 35],
  total: 0,
});
const { current_page } = toRefs(propData) 

const emit = defineEmits(["currentChange"]);

const handleCurrentChange = (val: number) => {
  emit("currentChange", val);
};


</script>

你可能感兴趣的:(vue3,vue.js,javascript,前端)