vuejs-阻止事件冒泡与默认行为

来源:互联网 发布:怎么用c语言输入n个数 编辑:程序博客网 时间:2024/05/29 10:12

vuejs-阻止事件冒泡与默认行为


阻止事件冒泡:@click 改成@click.stop

<div id="box">    <div @click="show2()">        <input type="button" value="按钮" @click="show()">   // @click.stop="show()"    </div></div>
  • 1
  • 2
  • 3
  • 4
  • 5
new Vue({    el: "#box",    data: {},    methods: {        show: function() {            alert(1);         },        show2: function() {            alert(2);         }    }});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

在上面的代码中,input元素绑定了一个click事件,点击它将调用show()方法

同时其父节点也绑定了一个click事件,点击它将调用show2()方法

此时如果点击input按钮,将引发事件冒泡,show()和show2()方法会被依次调用

若要阻止事件冒泡,只需将input标签中的@click 改成@click.stop 即可

阻止默认行为:@contextmenu 改成@contextmenu.prevent

<div id="box">    <input type="button" value="按钮" @contextmenu="show()">   // @contextmenu.prevent="show()"</div>
  • 1
  • 2
  • 3
new Vue({    el: "#box",    data: {},    methods: {        show: function() {            alert(1);         }    }});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

在上面的代码中,input元素绑定了一个contextmenu事件,单击鼠标右键会触发该事件,并调用show()方法

此时浏览器窗口不仅会出现alert弹框,还会出现浏览器默认的菜单选项

若要阻止默认行为,只需将@contextmenu 改成@contextmenu.prevent 即可

原创粉丝点击