如何在Vue中实现默认显示9项的‘显示更多’按钮功能
Vue实现“显示更多”列表功能解决方案
原代码问题分析
- 未定义控制显示数量的响应式变量(
cardVisible/limit) - 组合式API中错误使用
this(Vue3组合式API无需通过this访问变量) - 按钮放在
v-for循环内会重复渲染,逻辑位置错误 - 切片逻辑未绑定正确的控制变量
修正后的完整代码
Script 部分
import { ref, computed } from "vue"; // 默认展示9个,响应式控制变量 const cardVisible = ref(9); // 模拟完整列表数据(原数据不足9个,新增部分数据便于测试) const cards = ref([ { key: 1, judul: "Frontend"}, { key: 2, judul: "Backend"}, { key: 3, judul: "UI/UX"}, { key: 4, judul: "Product Manager"}, { key: 5, judul: "Product Manager"}, { key: 6, judul: "DevOps"}, { key: 7, judul: "Data Analyst"}, { key: 8, judul: "QA"}, { key: 9, judul: "Mobile Developer"}, { key: 10, judul: "Fullstack Developer"}, { key: 11, judul: "Cybersecurity"}, ]); // 计算属性:动态获取要显示的列表项 const visibleCards = computed(() => { return cards.value.slice(0, cardVisible.value); }); // 显示更多:点击后直接展示所有剩余项 const showMore = () => { cardVisible.value = cards.value.length; };
Template 部分
<!-- 循环渲染可见的列表项 --> <div class="collaps" v-for="card in visibleCards" :key="card.key"> {{ card.judul }} </div> <!-- 仅当还有未显示项时展示按钮 --> <button @click="showMore" v-if="cardVisible < cards.length" > 显示更多 </button>
可选:逐步加载(每次显示额外5项)
如果需要实现每次点击加载5项而非一次性显示全部,只需修改showMore方法:
const step = 5; const showMore = () => { // 限制最大显示数量不超过列表总长度 cardVisible.value = Math.min(cardVisible.value + step, cards.value.length); };
内容的提问来源于stack exchange,提问作者Pahreza Iqbal Prastowo
相关产品推荐
相关产品推荐

