Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

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
},

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...