Vue-vue中事件的定义和使用

1.vue中事件的基础定义与使用(结合案例分析)
在vue中事件定义存在两种方法:
a.函数名:function(){}
b.函数名(){}

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>vue事件绑定</title>
</head>
<body>
<!--1.页面提供按钮
2.按钮绑定单击事件
在单击事件中修改年龄的值,同时渲染页面-->
<div id="app">
    <h2>年龄:{
   
   {age}}</h2>
    <br>
<!--    v-on报红,alt+enter-->
    <input type="button" value="通过v-on,使年龄每次+1" v-on:click="changage">
    <input type="button" value="通过@,使年龄每次-1" @click="changage2">

</div>
<!--vue中事件的简化写法-->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    const app=new Vue({
     
     
        el:"#app",
        data:{
     
     
            msg:"你好",
            age:1
        },
        methods:{
     
        //methods,定义vue事件
            changage:function () {
     
     
                //在函数中获取vue实例中data数据,在事件函数中this就是vue实例
                // console.log(this);
                this.age=this.age+1;
                // this.age++;
                // alert("改变年龄");
            },
            // changage2:function () {
     
     
            //     this.age=this.age-1;
            //
            // },
            //还可以这样简化事件

            changage2(){
     
     
                if (this.age>1){
     
      //age必须大于0
                    this.age--;
                }

            }
        }
    })
</script>
</body>
</html>

2.vue中事件参数的传递

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>vue事件绑定</title>
</head>
<body>
<div id="app">
    <h2>年龄:{
   
   {age}}</h2>
    <br>
    <input type="button" value="改变年龄为指定的值" @click="changage(22,'xiaowen')">

</div>
<!--vue中事件的简化写法-->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    const app=new Vue({
     
     
        el:"#app",
        data:{
     
     
            age:1
        },
        methods:{
     
        //methods,定义vue事件
            changage:function (age,username) {
     
     
                this.age=age;
                alert(username)
            }
            // changage2(age,username) {
     
     
            //     this.age=age;
            //     alert(username) 
            // }
        }
    })
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/dgssd/article/details/111037587