实现思路:组件挂载后执行初始化操作,初始化添加事件监听器,当浏览器窗口大小发生变化时会调用这个函数handleResize
<el-pagination v-model:current-page="currentPage" background :total="total" layout="prev, pager, next"class="pagination" :page-size="pageSize" :pager-count="3"></el-pagination>
import { reactive, ref, computed, onMounted, onUnmounted } from 'vue' const total = ref(30);const pageSize = ref(10);const currentPage = ref(1);const pagedHonorList = computed(() => {const startIndex = (currentPage.value - 1) * pageSize.value;const endIndex = startIndex + pageSize.value;return honorList.slice(startIndex, endIndex);});// 动态计算宽度 当屏幕分辨率 =< 430px时候使用其他组件 const screenWidth = ref(window.innerWidth);//处理窗口大小变化的逻辑 const handleResize = () => {screenWidth.value = window.innerWidth;if (screenWidth.value == 1024) {pageSize.value = 8} else if (screenWidth.value == 768) {pageSize.value = 6} else if (screenWidth.value <= 430) {pageSize.value = 4}// 将 pageSize 存储到本地存储localStorage.setItem('pageSize', pageSize.value.toString());}; onMounted(() => {//动态计算宽// 在页面加载时尝试从本地存储中读取 pageSizeif (localStorage.getItem('pageSize')) {const pageNumber = localStorage.getItem('pageSize')!pageSize.value = parseInt(pageNumber)} //初始化添加事件监听器,当浏览器窗口大小发生变化时会调用这个函数handleResize window.addEventListener('resize', handleResize);});