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

一、阻止事件冒泡:

<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 即可

---------------------
作者:Lewis_1993
来源:CSDN
原文:https://blog.csdn.net/Levis_1993/article/details/72485224 

原文地址:https://www.cnblogs.com/liAnran/p/10067696.html