passive的作用
让事件的默认行为立即执行,无需等待事件回调执行完毕
比如滚动事件:默认情况下,浏览器会等待JavaScript事件处理函数(onscroll) 执行完毕后才进行滚动,这可能会导致页面的滚动不够流畅。
使用passive会立即让滚动条滚动,不需要等待滚动条事件执行完再让滚动条滚动。
function demo(){
for (let i = 0; i < 200000; i++) {
console.log('#'+ i)
}
}
<div style="overflow: scroll;border: 10px dotted blue;height: 400px;" @scroll.passive="demo">
<ol>
<li v-for="n in 50">{{ n }}</li>
</ol>
</div>
可以看到在设置了passive后,滚动条会先滚动再执行回调函数。
而不设置passive时,必须等待回调函数执行完毕后再滚动滚动条,所以给用户的体验不好。
为了避免这一问题,大部分浏览器(Safari 和 Internet Explorer 除外)将文档级节点 Window、Document 和 Document.body 上的 wheel、mousewheel、touchstart 和 touchmove 事件的 passive
默认值更改为 true
。如此,事件监听器便不能取消事件,也不会在用户滚动页面时阻止页面呈现。
window.addEventListener('wheel', (event) => {
for(var a=0;a<20000;a++) {
console.log('window', a)
}
}, { passive: true });
passive: true 时页面滚动比较丝滑,而设为 false时页面滚动就比较卡顿
但是 scroll 事件不受影响