vue获取元素高度提示undefined

\#\#\# 问题描述
在使用滚动监听的页面。offsetHeight使用正常。再切换到其他页面后提示"Uncaught TypeError: Cannot read property 'offsetHeight' of undefined"。再切换回原页面后同样报错

\#\#\# 问题出现的环境背景及自己尝试过哪些方法
image.png
\#\#\# 相关代码
粘贴代码文本(请勿用截图)
mounted() {

window.addEventListener('scroll', this.handleScroll, true)

},
methods: {

// 监控页面滚动
handleScroll() {
  var top = Math.floor(
    document.body.scrollTop ||
    document.documentElement.scrollTop ||
    window.pageXOffset
  )
  const height = this.$refs.btns.offsetHeight
  console.log(height)
  this.fixed = top > 243 + height
},

\#\#\# 你期待的结果是什么?实际看到的错误信息又是什么?
如何解决报错

阅读 5.9k
1 个回答

你切换到其他页面没卸载监听器吧。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题