事件处理

1.v-on指令监听DOM事件,并在触发时运行一些JavaScript代码。

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>学习example</title>
    <script src="../static/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
    <button v-on:click="counter+=1">{{counter}}</button>
</div>

<script type="text/javascript">
    var vm = new Vue({
        el: "#app",
        data: {
            counter: 0,
        },
    });
</script>
<style type="text/css">
</style>
</body>
</html>

2.事件处理方法

许多事件处理逻辑会更为复杂,所以直接把 JavaScript 代码写在v-on指令中是不可行的。因此v-on还可以接收一个需要调用的方法名称。

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>学习example</title>
    <script src="../static/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
    <button v-on:click="greet">greet</button>
</div>

<script type="text/javascript">
    var vm = new Vue({
        el: "#app",
        data: {
            name: "vue",
        },
        methods: {
            greet: function (even) {
                //`this` 在方法里指向当前 Vue 实例
                alert("hi " + this.name);
                if (even) {
                    alert(even.target.tagName);
                }
            }
        }
    });
</script>
<style type="text/css">
</style>
</body>
</html>

 3.内联处理器中的方法

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>学习example</title>
    <script src="../static/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
    <button v-on:click="say('hi')">say hi</button>
    <button v-on:click="say('what')">say what</button>
</div>

<script type="text/javascript">
    var vm = new Vue({
        el: "#app",
        methods: {
            say: function (str) {
                alert(str);
            }
        }
    });
</script>
<style type="text/css">
</style>
</body>
</html>

 4.在内联语句处理器中访问原始的 DOM 事件。可以用特殊变量 $event 把它传入方法。

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>学习example</title>
    <script src="../static/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
    <button v-on:click="say('hello',$event)">say hello</button>
</div>

<script type="text/javascript">
    var vm = new Vue({
        el: "#app",
        methods: {
            say: function (str, e) {
                alert(str);
                alert(e);
                console.log(e);
            }
        }
    });
</script>
<style type="text/css">
</style>
</body>
</html>

 

posted on 2020-07-31 10:47  lina2014  阅读(35)  评论(0编辑  收藏  举报

导航