我在 VueJs/Gridsome 中构建了一个组件,用于使用 locomotive-scoll 平滑页面滚动。在初始页面加载或硬页面重新加载时它工作正常,但仅在更改路由时就不行。我尝试了几种方法,例如向组件添加密钥或使用 watch 方法,但似乎没有任何效果。
自定义滚动.vue
<template>
<div></div>
</template>
<script>
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger);
import LocomotiveScroll from "locomotive-scroll";
export default {
name: "CustomScroll",
data() {
return {
// x: null,
};
},
methods: {
scrollMeTo(target, duration) {
let z = this.x;
z.scrollTo(target, duration);
},
initScroll() {
const locoScroll = new LocomotiveScroll({
el: document.querySelector("[data-scroll-container]"),
smooth: true,
});
this.x = locoScroll;
ScrollTrigger.scrollerProxy("[data-scroll-container]", {
scrollTop(value) {
return arguments.length ? locoScroll.scrollTo(value, 0, 0) : locoScroll.scroll.instance.scroll.y;
},
getBoundingClientRect() {
return {
top: 0,
left: 0,
width: window.innerWidth,
height: window.innerHeight,
};
},
pinType: document.querySelector("[data-scroll-container]").style.transform ? "transform" : "fixed",
});
// --- scrollTrigger update, do not move this --- //
ScrollTrigger.addEventListener("refresh", () => locoScroll.update());
ScrollTrigger.refresh();
},
},
mounted() {
this.initScroll();
},
};
</script>
引用组件的 Default.vue:
<template>
<div class="layout">
<Header />
<main>
<slot />
</main>
<CustomCursor />
<CustomScroll ref="scroller" />
</div>
</template>
<static-query>
query {
metadata {
siteName,
siteDescription,
siteUrl
}
}
</static-query>
<script>
import CustomCursor from "~/components/CustomCursor.vue";
import CustomScroll from "~/components/CustomScroll.vue";
import Header from "~/components/Header.vue";
import Footer from "~/components/Footer.vue";
export default {
components: {
CustomCursor,
CustomScroll,
Header,
Footer,
},
};
</script>