vue .passive的作用

vue中的passive

vue的文档中提到

Vue 还对应 addEventListener 中的 passive 选项提供了 .passive 修饰符。

但对其passive的作用并未提及,其实文档中有暗示,点击addEventListener或者passive可以跳转到MDN文档
在这里插入图片描述
点击passive,跳到mdn文档。

passive: Boolean,设置为true时,表示 listener 永远不会调用 preventDefault()。如果 listener 仍然调用了这个函数,客户端将会忽略它并抛出一个控制台警告。

passive表示listener函数不会调用preventDefault(),那么它的应用场景是什么?又查到What are passive event listeners?

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is
promising the handler won’t call preventDefault to disable scrolling.
This frees the browser up to respond to scrolling immediately without
waiting for JavaScript, thus ensuring a reliably smooth scrolling
experience for the user.

将上文提到的问题和答案翻译过来就是


问题:所有的现代浏览器,即使在很昂贵的js运行下,也会有一个线程式的滚动特性来允许流畅的滚动,但是,touchstart和touchmove调用preventDefault()能阻止滚动,所以这个滚动优化在有时候会被touchstart和touchmove的所限制。


解决:通过标识一个touch或者wheel监听器为passive,就等于开发者保证了监听器不会调用preventDefault()。浏览器解放了,不用等待js运行结果,就会立刻响应滚动,这就确保了流畅的滚动体验。

总结

passive主要用在移动端的scroll事件,来提高浏览器响应速度,提升用户体验。因为passive=true等于提前告诉了浏览器,touchstart和touchmove不会阻止默认事件,手刚开始触摸,浏览器就可以立刻给与响应;否则,手触摸屏幕了,但要等待touchstart和touchmove的结果,多了这一步,响应时间就长了,用户体验也就差了。

参考

What are passive event listeners?
vue中的.passive修饰符

发布了335 篇原创文章 · 获赞 369 · 访问量 193万+

猜你喜欢

转载自blog.csdn.net/wangjun5159/article/details/104251705