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修饰符

  • 9
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值