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

来源:互联网 发布:知肤泉水光面膜汞超标 编辑:程序博客网 时间:2024/06/09 20:24

阻止事件冒泡

<div id="box">    <div @click="show2()">        <input type="button" value="按钮" @click="show()">    </div></div>
new Vue({    el: "#box",    data: {},    methods: {        show: function() {            alert(1);         },        show2: function() {            alert(2);         }    }});

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

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

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

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

阻止默认行为

<div id="box">    <input type="button" value="按钮" @contextmenu="show()"></div>
new Vue({    el: "#box",    data: {},    methods: {        show: function() {            alert(1);         }    }});

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

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

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

原创粉丝点击