单选多选触发label的两次点击事件,label默认向input分派(dispatch)一次点击事件
<template> <!-- <div class="hello">hi</div> --> <div> <label for="a" @click=" (e) => { fun4(e); } " >aaa</label > <input id="a" type="radio" @input=" (e) => { fun1(e); } " @change=" (e) => { fun2(e); } " @click="fun3()" /> </div> </template> <script> export default { name: "HelloWorld", props: { msg: String, }, data() { return {}; }, methods: { fun1(e, data) { console.log("fun1", e, data); }, fun2(e, data) { console.log("fun2", e, data); }, fun3() { console.log("fun3"); }, fun4(e, data) { console.log("fun4", e, data); }, }, }; </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
依次触发:
fun4->3->1->2
label并没有包裹input,只是通过for指向了
如上:发现label只是触发了默认时间,其label本身的click并没有执行两次,那是为什么呢?
原因:input的点击事件并没有冒泡到label上,试试另外一种写法就会有了
<template> <!-- <div class="hello">hi</div> --> <div> <label @click=" (e) => { fun4(e); } " >aaa<input id="a" type="radio" @input=" (e) => { fun1(e); } " @change=" (e) => { fun2(e); } " @click="fun3()" /></label> </div> </template> <script> export default { name: "HelloWorld", props: { msg: String, }, data() { return {}; }, methods: { fun1(e, data) { console.log("fun1", e, data); }, fun2(e, data) { console.log("fun2", e, data); }, fun3() { console.log("fun3"); }, fun4(e, data) { console.log("fun4", e, data); }, }, }; </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
执行顺序:fun4-3-4-1-2
原因:label先执行本身的点击事件,在触发默认时间(可以用prevent阻止),导致input的click触发;再通过事件冒泡(可以用stop阻止),导致label上的click有触发一次