VUE框架的事件绑定与事件回调函数的this对象------VUE框架

凌得涂

关注

阅读 14

2024-01-09

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>
<body>
    <!-- Vue中完成事件绑定需要用v-on来实现 -->
    <div id="app">
        <h1>{{msg}}</h1>
        <!-- v-on处写的必须是JS表达式,普通的JS代码不行,VUE不认识,写成VUE所管理的也可以 -->
        <button v-on:click="sayHello">按一下</button>
        <button v-on:click="Hello">按一下</button>
        <!-- v-on的简写方法就是@click -->
        <button @click="Hi('Jack',$event)">按一下</button>
        <button @click="haha">哈哈哈</button>
        <button @click="sayWhat">sayWhat</button>
    </div>
    <script type="text/javascript">
        const vm = new Vue({
            el : "#app",
            data :{
                msg : "hELLO",
                // 这两种方法都可以实现
                sayHello : function()
                {
                    alert(123);
                }
            },
            methods : {
                Hello : function()
                {
                    alert("Hello");
                },
                Hi : function(name,event)
                {
                    alert(event);
                    alert("H1" + name);
                },
                haha : function()
                {
                    alert("哈哈哈");
                },
                // Vue再调用函数的是否,会自动传递一个参数,这个参数是当前发生的事件
                sayWhat : function(event)
                {
                    console.log(event.target.innerText)
                }
            }
        });
    </script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>
<body>
    <div id="app">
        <h1>{{msg}}</h1>
        <h1>计数器:{{value}}</h1>
        <button @click="Plus">点我哈</button>
    </div>
    <script>
        const vm = new Vue({
            el : "#app",
            data : {
                msg : "Hello Vue!",
                value : 1
            },
            methods : 
            {
                Plus()
                {
                    // vm.$data.value++;
                    this.value++;
                    // vm和this对象是同一个对象
                    console.log(vm === this);
                },
                add2:()=>
                {
                    // 箭头函数中没有this,箭头函数的this是从父级作用域继承过来的
                    // 对于当前程序来说,父级作用域是全局作用域window
                    console.log(this === vm);
                    this.value++;
                }
            }
        });
    </script>
</body>
</html>

精彩评论(0)

0 0 举报