我试图破坏并重新加载我的Flickity幻灯片,同时使用Swup进行页面转换,但我没有太多的运气。这是我的js文件:
import Swup from 'swup';
var Flickity = require('flickity');
function init() {
if (document.querySelector('.testimonials-slideshow')) {
var flkty = new Flickity('.testimonials-slideshow', {
wrapAround: true,
pageDots: false,
autoPlay: true,
arrowShape: 'M68.374,83.866L31.902,50L68.374,16.134L64.814,12.3L24.214,50L64.814,87.7L68.374,83.866Z'
});
}
}
function unload() {
flkty.destroy();
}
init();
const swup = new Swup();
swup.on('contentReplaced', init);
swup.on('willReplaceContent', unload);但是当我尝试这样做时,我得到了错误flkty is not defined。有人能在这方面给我一些建议吗?
发布于 2021-03-25 19:03:57
变量作用域
正如CBroe所提到的,您的var是未定义的,因为您定义它的位置。它是在一个函数中定义的,但应该在“顶层”定义。
import Swup from 'swup';
var Flickity = require('flickity');
// Added a "global" definition here:
var flkty;
function init() {
if (document.querySelector('.testimonials-slideshow')) {
// Removed var:
flkty = new Flickity('.testimonials-slideshow', {
wrapAround: true,
pageDots: false,
autoPlay: true,
arrowShape: 'M68.374,83.866L31.902,50L68.374,16.134L64.814,12.3L24.214,50L64.814,87.7L68.374,83.866Z'
});
}
}
function unload() {
flkty.destroy();
}
init();
const swup = new Swup();
swup.on('contentReplaced', init);
swup.on('willReplaceContent', unload);此外,如果您正在使用任何类型的模块捆绑器,有时它仍然会丢失,因此您可以考虑这样做:
window.flkty = new Flickity('.testimonials-slideshow', ...并且总是以这种方式引用它,即
window.flkty.destroy();仅销毁已存在的实例
这就是你的变量定义。下一个潜在的错误是,只有在查询选择器匹配时才初始化flkty:
if (document.querySelector('.testimonials-slideshow')) {但是您会在每个页面都销毁它,所以您可以检查一下"is it inited,this willReplaceContent load?“。在这种情况下,您可以执行如下检查:
// Init the var as false:
var flkty = false
function init() {
if (document.querySelector('.testimonials-slideshow')) {
flkty = new Flickity('.testimonials-slideshow', ...);
}
}
function unload() {
if(flkty){
flkty.destroy();
// Make sure the flkty var is set to false at the end:
flkty = false;
}
}整理你的代码
这一切可能会变得有点失控,所以我们开始做的是创建模块。下面是我们使用的一个carousel模块的框架:
// modules/Carousel.js
import Swiper from "swiper";
export default {
carouselEl: null,
carouselSwiper: null,
setup() {
this.carouselEl = document.getElementById("header-carousel");
if (!this.carouselEl) {
// Just stop if there is no carousel on this page
return;
}
this.carouselSwiper = new Swiper(this.carouselEl, { ... });
this.carouselSwiper.on("slideChange", () => { ... });
},
destroy() {
// If we already have one:
if (this.carouselSwiper) {
this.carouselSwiper.destroy();
}
// Make sure we are reset, ready for next time:
this.carouselSwiper = null;
},
};然后,在我们的main.js中,我们做一些像你这样的事情:
import Carousel from "./modules/Carousel.js";
function init(){
Carousel.setup();
// Add more here as the project grows...
}
function unload(){
Carousel.unload();
}
swup = new Swup();
swup.on("contentReplaced", init);
swup.on("willReplaceContent", unload);
init();所有模块都有setup和unload函数,如果元素不存在,它们也不会中断,因此我们可以在每个页面加载和卸载时调用所有这些函数。
我喜欢swup,但也有在噩梦中启动和销毁东西的个人经验,所以如果你需要任何进一步的帮助,请告诉我。
https://stackoverflow.com/questions/66748654
复制相似问题