我有一个非常奇怪的问题,我无法解决。
我正在使用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)
但是导入必须是顶级的。
请问有什么建议吗?我正要通过窗外的电脑。大概是好事。