【问题】
使用addEventListener监听滚动来阻止冒泡(e.preventDefault()),removeEventListener移除监听阻止冒泡(e.preventDefault()),但未生效。
错误代码示例如下:
// 在 onMounted 钩子中监听
document.body.addEventListener('touchmove', function(e) {
e.preventDefault()
}, { passive: false })
// 在 onBeforeUnmount 钩子中移除监听
document.body.removeEventListener('touchmove', function(e) {
e.preventDefault()
}, { passive: false })
【解决】
正确代码示例如下:
- 先把e.preventDefault()单独写一个方法
const noScroll = (e) => {
e.preventDefault()
}
- 然后把noScroll方法当作addEventListener及removeEventListener的第二个参数
// 在 onMounted 钩子中监听
document.body.addEventListener('touchmove', noScroll, { passive: false })
// 在 onBeforeUnmount 钩子中移除监听
document.body.removeEventListener('touchmove', noScroll, { passive: false })
注: 第三个参数passive默认值为false,但是chrome, Firefox等浏览器为了保证滚动时的性能,在Window,、Document、 Document.body上针对 touchstart 和 touchmove 事件将passive默认值改为了true。
详细可参考:
EventTarget.addEventListener()
EventTarget.removeEventListener