【发布时间】:2020-09-09 22:14:20
【问题描述】:
我有一个非常奇怪的问题,我无法解决。
我正在使用Barba.js,它可以进行很棒的页面转换,而Swiper.js 是一个可爱的轮播。问题是它使您的页面成为 SPA,因此您必须重新init 脚本。告诉你真相很痛苦。
在我的 barba.js 文件中,我在顶部调用了一个 swiper carousel
import barba from "@barba/core";
import { homeCarousel } from './swiper.js'
function initCarousel() {
if (document.querySelector('.swiper-container') != null) {
homeCarousel();
}
}
barba.init({
sync: true,
preventRunning: true,
views: [{
namespace: 'main',
afterEnter() {
setTimeout(() => {
initCarousel();
}, 550);
}
}],
transitions: [{
async leave() {
done();
},
async enter() {
newPage();
},
}]
})
然后在我的 swiper.js 文件中
import Swiper from 'swiper';
import 'swiper/css/swiper.css';
const homeCarousel = () => {
var hs = new Swiper('.home__carousel', {
init: false,
});
hs.init();
}
homeCarousel();
export { homeCarousel }
这一切正常。但我有另一个页面没有轮播,所以.swiper-container 将返回null。这也很好,但是因为我在 barba.js 的顶部导入
import { homeCarousel } from './swiper.js'
在页面刷新时调用它会导致严重的错误
Cannot read property 'push' of undefined
当路由改变时,没有可怕的控制台错误。
我想在理想情况下我会将此导入语句放在 if (document.querySelector('.swiper-container') != null) 中,但导入 必须 是顶级的。
有什么建议吗?我正要通过窗外的电脑。可能是件好事。
【问题讨论】:
-
为什么在 swiper.js 中调用 homeCarousel?看起来它是一个库,所以它应该只提供 API。
-
@Orphy 哦,天哪。你太棒了。真的非常感谢。请将此作为我会接受的答案。
标签: javascript barbajs