How to use methods in Vue, read it quickly in three minutes

1. Methods method application scenarios:

In Vue, when we need to call a method, we need to define these methods in the methods attribute before calling the method in the vue expression.


2. How to use the methods method

The syntax is defined as follows:

<script>
    //创建vue对象
    new Vue({
       el: "#app",//将id=app的div的管理权交给Vue
       
       methods:{//在此处声明所有的方法
           方法名1(){//点击对应按钮后执行
              
           },

           方法名2() {
              
           }
       }
    });
</script>

Below we give a small example.

When we call the doAdd method, we need to define the method in methods first.

Then we can use @click="doAdd" in the button to call the method

  <div class="row">
     <div class="col-md-4 col-md-offset-4" style="margin-top: 20px;text-align: center;">
      //该处调用了doAdd方法
     <button class="btn btn-primary" style="margin-right: 8px;"@click="doAdd">添加</button>
     <button class="btn btn-default">重置</button>
     </div>
</div>
 methods : {
         //这里面定义了一个doAdd的方法.
         doAdd(){
               var url = "user_adduser_name="+this.userName+"&nick_name="+this.nickName+"&sex="+this.sex
                    +"&phone="+this.phone+"&birth="+this.birth;
               console.log(url);
               //通过axios发送请求
                axios.get(url).then(response =>{
                    console.log(response.data);
                    if (response.data == 'true'||response.data == true) {
                        window.location.href = 'user_list.html';
                    }else {
                        alert("添加用户失败!");
                    }
                });
            }
        }


3. Points to note:

In a method, this points to the instance to which the method belongs by default, and you can use this to access attributes in data or other methods

but!!!!!

Do note that the method cannot use the arrow function, because the this of the arrow function is not a Vue instance, (for example, do: () => this.a)

Reason: The arrow function is bound to the context of the parent scope. In this case, this will not point to the Vue instance by default, and an error will be reported when this.a is running. The reason for the error is a undefined (a is not defined)

I hope the above sharing can be helpful to everyone.

 

Guess you like

Origin blog.csdn.net/qq_42176665/article/details/127776349