SoFunction
Updated on 2025-03-02

Detailed explanation of Vue calculation attributes and monitoring attribute implementation methods

1. Calculate properties

In development, there can be such a requirement. In the attribute (date), there are two attributes: fistName and lastName. The two attributes need to be spliced ​​together. This requirement is also very simple. There is the following implementation method

1. Interpolation syntax implementation

Stitch two data directly in body

    <div >
        surname:<input type="text" v-model="fistName"><br><br>
        name:<input type="text" v-model="lastName"><br><br>
        surnamename:<span>{{fistName + lastName}}</span>
    </div>

2. Implement through methods

Write a method that returns a string with the value spliced ​​together

    <div >
        surname:<input type="text" v-model="fistName"><br><br>
        name:<input type="text" v-model="lastName"><br><br>
        <!-- As long as the data changes,This method will be called again -->
        surnamename:<span>{{fullName()}}</span>
    </div>
    new Vue({
        el:'#root',
        data:{
            fistName:'open',
            lastName:'three'
        },
        methods: {
            fullName(){
                return  + ;
            }
        },
    })

3. Calculate attributes

The computed attribute is computed in vue, which stores the computed attributes.

The properties in data are different

    <div >
        surname:<input type="text" v-model="fistName"><br><br>
        name:<input type="text" v-model="lastName"><br><br>
        surnamename:<span>{{fullName}}</span>
    </div>
const vm = new Vue({
        el:'#root',
        //property        data:{
            fistName:'open',
            lastName:'three'
        },
        // Calculate properties        computed:{
            fullName:{
                //When someone reads fullName, get will be called and the return value of fullName                //Get call time                //1. Read fullName for the first time                //2. When the data depend on changes                get(){
                    //This here refers to vm                    return  + ;
                },
                //Called when fullName is called                set(value){
                    const arr = ('-')
                     = arr[0]
                     = arr[1]
                }
            }
        }
    })

There is a little difference in how calculation attributes and methods are written

  • {The method in {}} is written in a method, that is, with brackets
  • However, only the name is required to be written in the calculation attribute without curly braces

There are two methods to write in the calculation attribute, one is the get method and the other is the set method.

  • When someone reads the computed property of fullname, the get method will be called, and the return value is the value of fullname
  • When someone modify the calculation property of fullname, the set method will be called

When it is clear that there is only the get method and no set method is needed, the computed attribute can be abbreviated as follows:

            fullName(){
                return  + ;
            }

When will the get function be executed:

  • It will be executed once during the first read
  • It will be called once when the dependent data changes

Advantages of Computational Properties

Compared with the method, there is a caching mechanism (reuse) internal to the calculation attribute, which is more efficient and more convenient to debug.

Simply put, if the calculation attribute remains unchanged, the data of the calculation attribute will be stored in the cache. When other data on the page needs to read this calculation attribute, it no longer needs to be obtained from the vm, but directly obtained from the cache.

2. Monitoring attributes

Monitoring attributes can monitor changes in a certain attribute, and can obtain the values ​​before and after changes.

Implemented by keyword watch

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script type="text/javascript" src="../js/"></script>
  </head>
  <body>
    <div >
      <h2>The weather is very good today{{info}}</h2>
      <button @click="changgeWeather">Switch weather</button>
    </div>
  </body>
  <script>
     = false;
    const vm = new Vue({
      el: "#root",
      data: {
        isHot: true,
      },
      computed: {
        info() {
          return  ? "Hot" : "cool";
        },
      },
      methods: {
        changgeWeather() {
           = !;
        },
      },
      // Monitoring      //Applicable to know clearly who to monitor at the beginning      watch: {
        isHot: {
          //Let the handler call during initialization          immediate: true,
          //When will it be called?  When isHost changes          handler(newValue, oldValue) {
            ("isHost is called", newValue, oldValue);
          }
        },
      // }
    });
  </script>
</html>

For example, as in the above case, when isHost is modified, the handler in isHost in the monitoring property will be called

The function of immediate: true is to call this monitoring property when initializing it

Note that monitoring attributes must exist before monitoring can be performed.

In addition to the above evil writing method, you can also monitor it through vm.$watch

    vm.$watch("isHost", {
      //Let the handler call during initialization      immediate: true,
      //When will it be called?  When isHost changes      handler(newValue, oldValue) {
        ("isHost is called", newValue, oldValue);
      },
    });

The two use occasions are different:

  • The first one is that it is clear from the beginning that this attribute needs to be monitored, so it is written in vue
  • The second is that you don’t know that this attribute needs to be monitored at the beginning, and then add it later, you can use vm.$watch

When the monitoring attribute only has handler, you can abbreviate it

watch: {
        isHot((newValue, oldValue)): {
            ("isHost is called", newValue, oldValue);
        }
}        

3. In-depth monitoring

Deep monitoring is mainly used for higher monitoring levels

 data: {
        isHot: true,
        number: {
          a: 1,
          b: 1,
        },
      }

For example, the number in this data needs to monitor the changes of a and b, and the monitoring attribute needs to be used

"": {
            handler(newValue, oldValue) {
              ("a changes", newValue, oldValue);
            },
          },

You can monitor a certain attribute in an object, and you can also operate as above. "Object. Attribute" means a certain attribute in the monitoring

At the same time, you can also monitor the changes in number, just turn on the depth inside

        number:{
          // means deep opening          deep:true,
          handler(){
            ("Number has changed");
          }

You can monitor a certain attribute in an object, and you can also operate as above. "Object. Attribute" means a certain attribute in the monitoring

At the same time, you can also monitor the changes in number, just turn on the depth inside

        number:{
          // means deep opening          deep:true,
          handler(){
            ("Number has changed");
          }

This is the end of this article about the detailed explanation of Vue computing attributes and monitoring attribute implementation methods. For more related contents of Vue computing attributes and monitoring attributes, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!