Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

vue 的事件修饰符 capture 到底怎么回事?

<div id="app">
<div @click="btn0" style=" width:300px;height:300px; border:1px solid red;background:#606060">0
<div @click.capture="btn1" style=" width:200px;height:200px; border:1px solid red;background:#CCC">1
<div @click="btn2" style=" width:100px;height:100px; border:1px solid red;background:#f5f5f5">2
  <button @click="btn3">3</button>
</div>
</div>
</div>
   </div>
<script src="https://cn.vuejs.org/js/vue.min.js"></script>
<script>
let vm=new Vue({
el:'#app',
   data:[],
    methods:{
        btn0(){
          alert('btn0')
           },
        btn1:function(){
            alert('btn1')
        },
        btn2:function(){
            alert('btn2')
        },
 btn3:function(){
            alert('btn3')
        }
    },
})
</script>

点击按钮之后事件触发的顺序
btn1->btn3->btn2->btn0
如果把 capture放在 btn2上面,则事件触发的顺序变成了:
btn2->btn3->btn1->btn0

最后总结的优先级规律是:

  1. 设置了capture的
  2. 真正被点击的
  3. 结束了capture之后,依照冒泡顺序
  4. 已经出发的事件(capture),在冒泡阶段会忽略不再触发

这个结论对不对,为什么会这样?


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

1 Answer

0 votes
by (71.8m points)

顺序其实就是:

  • 从外到内的事件捕获顺序执行有 capture 的元素click事件
  • 再从点击的元素开始,从内到外事件冒泡顺序执行 click 事件(过滤掉已捕获的元素)

demo链接:
https://codepen.io/liangxh052...
参考链接;
https://cn.vuejs.org/v2/guide...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...