乐趣区

vue-02-事件处理

1. 绑定监听

v-on:xxx=”fun”
@xxx=”fun”
@xxx=”fun(参数)”
默认事件形参: event
隐含属性对象: $event

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> 绑定监听 </title>
</head>
<body>
<div id="demo">
    <button @click="test1">test1</button>
    <button @click="test2('abc')">test2</button>
    <button @click="test3">test3</button>
    <button @click="test4('abcd',$event)">test4</button>

</div>
<script type="text/javascript" src="../vue.js"></script>
<script type="text/javascript">
    new Vue({
        el: '#demo',
        data: {},
        methods: {test1() {//@xxx="fun"
                alert('test1');
            },
            test2(msg) {// @xxx="fun( 参数)"
                alert(msg);
            },
            test3(event) {// 默认事件形参: event
                alert(event.target.innerHTML);
            },
            test4(msg, event) {// 隐含属性对象: $event
                alert(msg + '---' + event.target.textContent);
                // alert(msg + '---' + event.target.innerHTML); 效果等同
            }
        }
    })
</script>
</body>
</html>

结果:

2. 事件修饰符

  • prevent 阻止事件的默认行为
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> 事件修饰符 prevent</title>
</head>
<body>
<div id="demo">
    <a href="http://www.baidu.com" @click.prevent="test1"> 百度一下 </a>
</div>
<script type="text/javascript" src="../vue.js"></script>
<script type="text/javascript">
    new Vue({
        el: '#demo',
        data: {},
        methods: {test1() {alert('点击了链接');
            }
        }
    })
</script>
</body>
</html>

结果:正常情况下,点击了链接,会跳转到相应的地址。由于使用了 prevent,阻止了跳转链接的默认行为。

  • stop 停止事件冒泡
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> 事件修饰符 stop</title>
</head>
<body>
<div id="demo">
    <div style="background: pink; width : 200px; height: 200px" @click="test1">
        <div style="background: skyblue; width: 100px; height: 100px" @click.stop="test2"></div>
    </div>
</div>
<script type="text/javascript" src="../vue.js"></script>
<script type="text/javascript">
    new Vue({
        el: '#demo',
        data: {},
        methods: {test1() {alert('out');
            },
            test2() {alert('inner');
            }
        }
    })
</script>
</body>
</html>

结果:如果不加 stop,则点击蓝色的框后,会 alert inner 和 out。如果加了 stop, 则只会 alert inner。

退出移动版