如何在 NUXTjs 中跳转到其他页面时解绑事件?



我在一页中编写了这段代码。它有效,但是当我跳转到其他页面时如何取消绑定此事件?

private mounted () {
if (process.browser) {
const banner:any = document.querySelector('.banner img')
document.addEventListener('scroll', () => {
const offsetTop = window.scrollY
const INTOR_HEIGHT = document.querySelector('.intro-text').offsetHeight
if (offsetTop < INTOR_HEIGHT) {
banner.style.top = offsetTop + 'px'
}
})
}
}

当我从此页面跳转到其他页面时,会抛出此错误:

javascript uncatch TypeError: 无法读取属性 'offsetHeight' 的 零 at HTMLDocument.eval

哈哈,VUE.js实例生命周期钩子也可以在nuxt.js中使用。 所以就像这样

private smoothSlier () {
const banner:any = document.querySelector('.banner img')
const offsetTop = window.scrollY
const INTOR_HEIGHT:any = document.querySelector('.intro-text').offsetHeight
if (offsetTop < INTOR_HEIGHT) {
banner.style.top = offsetTop + 'px'
}
}
private mounted () {
if (process.browser) {
document.addEventListener('scroll', this.smoothSlier)
}
}
private beforeDestroy () {
document.removeEventListener('scroll', this.smoothSlier)
}

重点是在挂载的钩子中绑定 golbal 事件,在之前取消绑定销毁

最新更新