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
981 views
in Technique[技术] by (71.8m points)

vue添加的监听事件无法移除

vue里面用了keep-alive缓存

在A页面添加了一个滚动监听window.addEventListener('scroll'()=>{})

因为用了缓存,beforeDestroy(),destroyed(),这两个方法就用不了。

然后我在app.vue里面写了个监听路由的,判断路由,离开了A页面就取消滚动监听事件window.removeEventListener('scroll',()=>{})

然后测试了一下,发现取消监听没反应,有没有大神知道怎么做?望指教一下

image
image
image


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

1 Reply

0 votes
by (71.8m points)

使用了 keep-alive, 离开A页面时,因为组件没被销毁,被缓存起来了,所以不会调用 beforeDestroy 和 destroyed 钩子。
在 keep-alive 中创建的组件,会多出两个生命周期的钩子: activated 与 deactivated:
activated:在 keep-alive 组件激活时调用
deactivated:在 keep-alive 组件停用时调用

当首次进入组件时:

  • beforeRouteEnter > beforeCreate > created > mounted > activated > ... ... > beforeRouteLeave > deactivated

再次进入组件时:

  • beforeRouteEnter > activated > ... ... > beforeRouteLeave > deactivated

所以可以通过组件内导航守卫结合activated,deactivated来设置添加或取消监听


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

...