Hugo页面无限滚动实现求助:无分页地址场景解决方案
无分页场景下的Hugo无限滚动加载实现方案
因为你的内容是无分页的连续流,不需要请求下一页接口,直接通过前端预加载所有内容+滚动触发逐步显示就能实现无限加载,结合现有Alpine.js的代码,修改步骤如下:
1. 调整Alpine.js状态与滚动监听逻辑
在x-data中添加滚动加载相关的状态变量和监听函数,同时在过滤条件变化时重置加载进度:
x-data="{ data: {}, filterApplied: false, currentCount: 5, // 初始显示数量 loadStep: 5, // 每次加载的数量 selectedStudy(id) { let selected = false; if (!this.data.studies) return false; this.data.studies[id].forEach(category => { if (!! this.data.categories[category].selected) selected = true; }); return selected; }, selectedCategoryType(category) { if (!this.data.categories || !this.data.categories[category]) return ''; return this.data.categories[category].selected; }, toggleCategory(category) { this.data.categories[category].selected = !this.data.categories[category].selected; let isFiltered = false; for (let c in this.data.categories) { if (this.data.categories[c].selected) { isFiltered = true; break; } } this.filterApplied = isFiltered; this.currentCount = 5; // 切换分类后重置加载进度 }, clearAll() { this.filterApplied = false; for (let category in this.data.categories) { this.data.categories[category].selected = false; } this.currentCount = 5; // 清除过滤后重置加载进度 }, initScrollListener() { window.addEventListener('scroll', () => { const wrapper = document.getElementById('wrapper'); const scrollPosition = window.scrollY + window.innerHeight; const wrapperBottom = wrapper.offsetTop + wrapper.offsetHeight; // 滚动到距离容器底部200px时触发加载 if (scrollPosition >= wrapperBottom - 200 && this.currentCount < Object.keys(this.data.studies).length) { this.currentCount += this.loadStep; } }); }, }" x-init="data = (await (await fetch('./index.json')).json()); initScrollListener()"
2. 修改文章渲染逻辑
移除first 5的限制,渲染所有文章,通过currentCount变量控制显示数量:
<div id="wrapper" class="infinite-scroll"> {{ range $index, $page := .Pages }} <div class="my-item content xl:grid xl:grid-cols-2 gap-20 pb-40" x-show="({{ $index }} < currentCount) && (!filterApplied || selectedStudy('{{ $page.File.UniqueID }}'))"> <div> <a class="cursor-pointer" href="{{ .Params.link }}"> <img class="w-full h-auto" src="{{ .Params.preview | absURL }}" alt=""> </a> </div> <div> <a class="cursor-pointer" href="{{ .Params.link }}"> <div class="flex flex-col gap-4"> <div class="green-bar hidden xl:block"></div> <h4 class="text-header-2-mobile xl:text-header-2 font-bold pt-8">{{ .Params.name }}</h4> <p class="text-base-mobile xl:text-header-5">{{ .Params.description }}</p> <div class="text-base-mobile xl:text-blog-metadata pt-8 flex"> <p class="xl:pt-0 pt-1.5">{{ .Params.author }} | <span class="ml-1">{{- .Date.Format "Jan 2, 2006" -}}</span> </p> </div> </div> </a> </div> </div> {{ end }} </div>
说明
- 所有文章会在页面加载时全部渲染,但通过
x-show初始只显示前5篇 - 当用户滚动到接近页面底部时,自动增加
currentCount,逐步显示更多文章 - 切换分类或清除过滤时,重置
currentCount为5,避免过滤后显示过多不符合条件的内容
内容的提问来源于stack exchange,提问作者vsemusvetu
相关产品推荐
相关产品推荐

