Laravel链接适配Swup模板问题:页面总是重载如何解决?
Swup集成Laravel路由后失效的解决方案
我开发的项目用Swup实现页面过渡效果,单独使用静态模板时功能正常,但将链接改为Laravel路由生成形式后,Swup完全失效,点击链接总是触发页面重载。相关代码如下:
底部导航代码
<div id="footer-bar" class="footer-bar-1 footer-bar-detached"> <a href="{{ route('store') }}" class="{{ Route::getCurrentRoute()->getName() === 'store' ? 'active-nav' : '' }} a-link"><i class="bi bi-cart"></i><span>Magasin</span></a> <a href="{{ route('statements') }}" class="{{ Route::getCurrentRoute()->getName() === 'statements' ? 'active-nav' : '' }} a-link"><i class="bi bi-graph-up"></i><span>Mes paiements</span></a> <a href="{{ route('home') }} " class="circle-nav-2 a-link"><i class="bi bi-house-fill"></i><span>Home</span></a> <a href="{{ route('payments.index') }}" class="{{ Route::getCurrentRoute()->getName() === 'payments' ? 'active-nav' : '' }} a-link"><i class="bi bi-receipt"></i><span>Payments</span></a> <a href="#" data-bs-toggle="offcanvas" data-bs-target="#menu-sidebar"><i class="bi bi-three-dots"></i><span>More</span></a> </div>
Swup配置代码
if(isAJAX === true){ if(window.location.protocol !== "file:"){ const options = { containers: ["#page"], cache:false, animateHistoryBrowsing: false, plugins: [ new SwupPreloadPlugin() ], linkSelector:'a:not(.external-link):not(.default-link):not([href^="https"]):not([href^="http"]):not([data-gallery])' }; const swup = new Swup(options); document.addEventListener('swup:pageView',(e) => { init_template(); }) } }
问题分析
- 链接选择器匹配失效:Swup的
linkSelector规则排除了所有以http/https开头的链接,而Laravel的route()生成的是完整域名的URL(如http://your-domain.com/store),这些链接会被Swup忽略,直接触发原生页面重载。 - Home路由URL存在空格:第三个链接的
href末尾多了一个空格,生成的URL格式异常,可能导致Swup无法正确识别。 - 路由名称判断错误:第四个链接的激活状态判断用了
payments,但实际路由名称是payments.index,会导致激活状态显示异常(不影响Swup功能,但属于代码瑕疵)。
解决方案
调整Swup的链接选择器
修改linkSelector规则,只排除外部域名的链接,保留同域的Laravel路由链接。可以替换为以下两种写法之一:写法一(精准匹配同域链接):
linkSelector: 'a:not(.external-link):not(.default-link):not([href^="https"]:not([href*="' + window.location.host + '"])):not([href^="http"]:not([href*="' + window.location.host + '"])):not([data-gallery])'写法二(简化逻辑,靠类标记外部链接):
linkSelector: 'a:not(.external-link):not(.default-link):not([data-gallery])'后续给真正的外部链接添加
external-link类即可,Swup会自动拦截所有同域路由链接。修复Home路由的空格问题
将第三个链接的代码修改为:<a href="{{ route('home') }}" class="circle-nav-2 a-link"><i class="bi bi-house-fill"></i><span>Home</span></a>去掉
route('home')后面的空格。修正路由名称判断
第四个链接的激活状态判断修改为:<a href="{{ route('payments.index') }}" class="{{ Route::getCurrentRoute()->getName() === 'payments.index' ? 'active-nav' : '' }} a-link"><i class="bi bi-receipt"></i><span>Payments</span></a>确保路由名称与实际定义一致。
验证步骤
- 清除浏览器缓存后重新加载页面
- 点击底部导航链接,观察是否触发Swup的页面过渡动画而非页面重载
- 打开浏览器控制台,检查是否存在Swup相关的报错信息,排查潜在问题
内容的提问来源于stack exchange,提问作者Alain Kazadi
相关产品推荐
相关产品推荐

