我正在寻找解决方案并提出了这个代码
methods: {
handleScroll () {
console.log(window.scrollY)
}
},
created () {
window.addEventListener('scroll', this.handleScroll);
},
destroyed () {
window.removeEventListener('scroll', this.handleScroll);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这对我不起作用.我也尝试将窗口更改为document.body.
错误消息是 Window is not defined
Vam*_*hna 12
window 未定义,因为nuxt JS是服务器端呈现的.
所以尝试使用process.browser变量
methods: {
handleScroll () {
console.log(window.scrollY)
}
},
created () {
if (process.browser) {
window.addEventListener('scroll', this.handleScroll);
}
},
destroyed () {
if (process.browser) {
window.removeEventListener('scroll', this.handleScroll);
}
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅链接
window在created或中使用或任何其他特定于浏览器的API beforeCreate会导致问题,因为平台特定的API(例如发生SSR的服务器)在服务器上不可用document或window不可用。而是将逻辑从创建移动到beforeMount。将其保留在创建状态并通过它进行检查也process.browser可以,但是不够干净,并且很容易导致混淆。
export default {
methods: {
handleScroll () {
// Your scroll handling here
console.log(window.scrollY)
}
},
beforeMount () {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
}
}
Run Code Online (Sandbox Code Playgroud)
只有created和beforeCreate在服务器和客户端双方上执行。因此,您无需在beforeMount或中监视ifs beforeDestroy。
进一步阅读有关支持SSR的Vue组件
| 归档时间: |
|
| 查看次数: |
5964 次 |
| 最近记录: |