问题描述
我已经搜索了一个解决方案并想出了这个代码
I've search for a solution and came up with this code
methods: {
handleScroll () {
console.log(window.scrollY)
}
},
created () {
window.addEventListener('scroll', this.handleScroll);
},
destroyed () {
window.removeEventListener('scroll', this.handleScroll);
}
不幸的是,这对我不起作用.我还尝试将窗口更改为 document.body.
Unfortunately, this doesn't work for me. I also tried to change window to document.body.
错误信息是Window is not defined
推荐答案
在 created
或 beforeCreate
中使用 window
或任何其他浏览器特定的 API> 会导致问题,因为诸如 document
或 window
之类的特定于平台的 API 在服务器上不可用(发生 SSR 的地方).相反,将逻辑从 created 移到 beforeMount
.将其保留在创建状态并通过 process.browser
进行检查也可以,但不够简洁,容易导致混淆.
Using window
or any other browser-specific API in created
or beforeCreate
will lead to problems because platform-specific APIs like document
or window
are not available on the server (where SSR happens). Instead, move the logic from created into beforeMount
. Leaving it in created and checking it via process.browser
would work as well but is not as clean and can lead to confusion easily.
export default {
methods: {
handleScroll () {
// Your scroll handling here
console.log(window.scrollY)
}
},
beforeMount () {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
}
}
只有 created
和 beforeCreate
在服务器端和客户端上执行.因此,您不需要保护 beforeMount
或 beforeDestroy
中的 ifs.
Only created
and beforeCreate
are executed on both sides, server and client. Therefore you don't need guarding ifs in beforeMount
or beforeDestroy
.
进一步阅读ssr-准备好的 Vue 组件
这篇关于如何在 vue nuxtjs 中监听滚动事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!