Vue listener watch

Keywords: html5

The listener listens for data changes in the data. If the data changes, it notifies the listener of the bound method to perform the corresponding operation. From this point, it is very similar to calculating attributes.

However, listeners also have their own unique application scenarios.

Perform asynchronous or expensive operations.

Next, let's take a look at the basic use of listeners

We use listeners to count the total number of people.

        Total number:{{totalCount}}

Define the totalCount attribute in data.

 data: {
          selectItem: "",
          num: 100,
          totalCount: 0

Use watch to listen for data changes in the users array.

 watch: {
          users: {
            immediate: true, //Execute now
            handler(newValue, oldValue) {
              this.totalCount = newValue.length + "personal";

When the users array changes, the handler function will be executed. At the same time, the immediate attribute is added, and the value of this attribute is true, which means that the listener will also be executed when initializing the binding. Because the watch will not execute when initializing the binding. It will not listen for execution until the monitored content changes.

The above is the basic use of the watch listener, but through this case, we find it more convenient to use the calculation attribute to count the total number of people.

Of course, the listener has its own application scenario. Its application scenario is to use the listener when executing asynchronous requests or operations with high overhead.

Next, let's experience the application scenario of the watch listener through a case.

Let's look at an asynchronous operation. That is, after the user enters the user name in a text box, he should send the entered user name to the server to check whether the user name has been occupied.

The specific implementation code is as follows:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <div id="app">
        <span>user name</span>
          <!--Used here lazy,Ensure that the corresponding operation is performed only after the text box loses focus-->
        <span><input type="text" v-model.lazy="uname" /></span>
    <script src="./vue.js"></script>
      const vm = new Vue({
        el: "#app",
        data: {
          uname: "",
          message: "",
        methods: {
          checkUserName: function (userName) {
            let that = this;
            setTimeout(function () {
              if (userName === "admin") {
                that.message = "User name already exists,Please change....";
              } else {
                that.message = "The user name can be used.....";
            }, 3000);
        watch: {
          uname: function (value) {
            //Call the background interface to verify that the user name is occupied
            this.message = "Verifying user name....";

The above example is to monitor whether the value of uname has changed through watch. If it has changed, send an asynchronous request to check whether the value in uname has been occupied.

Through the above case: we can see that the watch allows asynchronous operation, and the intermediate state can be set before we get the final result, which is impossible for the calculation attribute.

Finally, let's summarize the calculation properties and listeners and take a look at their application scenarios.

First: contextual differences:

watch is suitable for the case where a value changes and some other things need to be done. It is suitable for the case where a value affects multiple values.

For example, in the user name detection in the above case, an uname has changed, but many other things have been done here, such as modifying the value of message and sending asynchronous requests.

The calculated attribute: a value is derived from other values. If other values change, the corresponding value will also change. It is suitable for the case where multiple values affect one value.

For example, the following code:

        return this.firstName+' '+this.lastName

The second point: the calculation attribute has caching.

Because of this feature, if we can use computational attributes in practical applications, we will first consider using computational attributes.

Third: the listener option provides a more general method, which is suitable for asynchronous operations or operations with high overhead.

Posted by on Sat, 25 Sep 2021 16:34:36 -0700