如何添加show more、show less按钮并按交互规则分页渲染列表项
列表分页加载Show More功能实现方案
核心实现逻辑
- 维护
visibleCount变量控制当前渲染的条目数量,初始值设为10 - 列表渲染时仅取原始数据的前
visibleCount项进行展示 - 点击Show More按钮时将
visibleCount累加10,触发重新渲染即可加载更多条目 - 直接使用你已有的下一页标识属性(下文统一称
hasNextPage)控制按钮显隐,当hasNextPage === null时隐藏按钮
代码实现示例
原生JavaScript实现
<ul id="list-box"></ul> <button id="show-more" style="display: none;margin-top: 12px;">Show More</button> <script> // 模拟数据和已有的下一页标识 const totalList = Array.from({length: 42}, (_, idx) => `测试条目 ${idx + 1}`); let hasNextPage = true; // 该值为null时自动隐藏按钮 let currentShowCount = 10; // 渲染方法 function render() { const listDom = document.getElementById('list-box'); const btnDom = document.getElementById('show-more'); // 截取要展示的条目 const showList = totalList.slice(0, currentShowCount); listDom.innerHTML = showList.map(item => `<li>${item}</li>`).join(''); // 控制按钮显隐 btnDom.style.display = hasNextPage !== null ? 'inline-block' : 'none'; } // 初始化渲染 render(); // 按钮点击事件 document.getElementById('show-more').addEventListener('click', () => { currentShowCount += 10; // 后端分页场景可在此处调用下一页接口,将返回数据拼入totalList,同时更新hasNextPage的值 render(); }); </script>
React实现
import { useState } from 'react'; const ItemList = ({ allItems, hasNextPage }) => { const [showCount, setShowCount] = useState(10); const showList = allItems.slice(0, showCount); const handleLoadMore = () => { setShowCount(prev => prev + 10); // 后端分页场景:调用下一页接口,更新allItems和hasNextPage即可 }; return ( <div className="list-wrapper"> <ul> {showList.map((item, index) => ( <li key={index}>{item.content}</li> ))} </ul> {hasNextPage !== null && ( <button onClick={handleLoadMore} style={{marginTop: '12px'}}> Show More </button> )} </div> ); };
Vue实现
<template> <div class="list-wrapper"> <ul> <li v-for="(item, index) in showList" :key="index"> {{ item.content }} </li> </ul> <button v-if="hasNextPage !== null" @click="handleLoadMore" style="margin-top: 12px;" > Show More </button> </div> </template> <script setup> import { ref, computed } from 'vue'; const props = defineProps({ allItems: { type: Array, default: () => [] }, hasNextPage: { type: Boolean, default: null } }); const showCount = ref(10); const showList = computed(() => props.allItems.slice(0, showCount.value)); const handleLoadMore = () => { showCount.value += 10; // 后端分页场景:调用下一页接口,更新allItems和hasNextPage即可 }; </script>
特殊场景说明
如果你的数据是后端分页返回的,不需要一次性加载全量数据,点击Show More时直接调用下一页接口,将返回的新数据拼入现有展示列表,同时更新hasNextPage的值即可,无需维护showCount变量。
内容的提问来源于stack exchange,提问作者Fawaz ul Hassan virk
相关产品推荐
相关产品推荐

