vue calculated and monitored attributes

Calculation properties   - computed

Definition: the attribute to be used does not exist. It must be calculated from the existing attribute

Principle: the bottom layer uses getter s and setter s provided by the Object.defineproperty method  

The following case: calculate the full name by the following last name and first name  

Method 1: it can be used directly   The return expression of the methods function implements its function

<body>
    <div id="root">
        Last name:<input type="text" v-model="firstName"><br /><br />
        Name:<input type="text" v-model="lastName"><br /><br />
        Full name:<span>{{fullname()}}</span>
    </div>
</body>
<script>
    Vue.config.productionTip = false

    new Vue({
        el: '#root',
        data: {
            firstName: 'Zhang',
            lastName: 'three'
        },
        methods: {
            fullname() {
                //this now points to the Vue instance
                //Once the data in vue changes, the template will be called again
                return this.firstName +'-'+ this.lastName
            }
        }
    })
</script>

Method 2: using the calculated attribute to realize

Note that when abbreviated, it is a read-only property and cannot be modified, that is, the setter function cannot be implemented

<body>
    <div id="root">
        Last name:<input type="text" v-model="firstName"><br /><br />
        Name:<input type="text" v-model="lastName"><br /><br />
        Full name:<span>{{fullname}}</span><br /><br />
    </div>
</body>
<script>
    Vue.config.productionTip = false

    new Vue({
        el: '#root',
        data: {
            firstName: 'Zhang',
            lastName: 'three'
        },
        computed: {
            //Complete code
            // fullname: {
            //     //What does get do? When someone reads fullastName, get will be called, and the return value will be the value of fullastName
            //     //When is get called? When fullname is read for the first time, the data that 2] depends on is transformed
            //     get() {
            //         console.log(this);
            //         return this.firstName + '-' + this.lastName
            //     },
            //     //When is set called? When fullname is modified
            //     set(value) {
            //         console.log('set', value)
            //         const arr = value.split('-')
            //         this.firstName = arr[0]
            //         this.lastName = arr[1]
            //     }
            // },
            //Read only attribute, abbreviated
            fullname() {
                console.log(this);
                return this.firstName + '-' + this.lastName
            }
        }
    })
</script>

  For two methods:

In the above method, the full name can be obtained through the existing attributes. The difference between the function method and the attribute calculation method is as follows:

  • Functions-------   When the data in the data changes, fullname() will be called. If the input content is the same, fullname() will also be called. If it needs to be executed every time, the efficiency is very low
  • Calculation attribute ----------- there is a caching mechanism inside the calculation attribute: it is to cache the calculated attribute. In the next calculation, if there is this value in the cache, it can be used directly, so there is no need to calculate it every time, which greatly improves the efficiency and makes debugging more convenient

If the calculation attribute is to be modified, the set function must be written to respond to the modification, and the data in the set will change

Monitoring properties - watch

Use the following example to see what monitoring properties are

    <div id="root">
        <h1>Today's weather{{info}}</h1>
        <button @click='changeWheate'>Switch weather</button>
    </div>
    <script>
        Vue.config.productionTip = false
        const vm = new Vue({
            el: '#root',
            data: {
                isHot: true
            },
            //Calculation properties
            computed: {
                info() {
                    return this.isHot ? 'It's hot' : 'pleasantly cool'
                }
            },
            //Event function
            methods: {
                changeWheate() {
                    this.isHot = !this.isHot
                }
            },
            //Monitoring attribute writing method I
            watch: {
                isHot: {
                    immediate: true,//Let the handler call once during initialization
                    handler(newValue, oldValue) {
                        console.log('It was modified', newValue, oldValue);
                    }
                }
            },
        })
        //Monitoring attribute writing method 2
        vm.$watch('isHot', {
            immediate: true,//Let the handler call once during initialization
            handler(newValue, oldValue) {
                console.log('It was modified', newValue, oldValue);
            }
        })
    </script>

When the monitoring property isHot changes, the handler function will be triggered to execute the statements inside  

We know that Vue itself can monitor changes in the internal settings of objects, but the watch provided by Vue is not allowed by default

But it doesn't matter: there is a way for the watch to monitor deeply  

  t by adding deep:true, you can make the watch realize deep monitoring

const vm = new Vue({
            el: '#root',
            data: {
                isHot: true,
                numbers: {
                    a: 1,
                    b: 1
                }
            },
           watch: {
                numbers:{
                  immediate: true,//Let the handler call once during initialization
                  deep:true,//Depth monitoring
                  handler(){
                          console.log("numbers Changed");
                  }
           }
       }
})

Summary:

  1. When the monitored properties change, the callback function will be called automatically for related operations
  2. The monitored property must exist for monitoring

There are two ways to write monitoring:

  • Pass in the watch configuration when new Vue
  • vm.$watch monitoring

immediate:true ------------- it means that the handler is called once during initialization. The default value is false

deep:true ------------- indicates that deep monitoring can monitor changes in internal values of objects - multi tier

The handler function is written into the monitoring property

The difference between computed and watch  

difference:

  1. The functions that can be completed by computed and watch can be completed
  2. The functions that can be completed by watch may not be completed by computed. For example, watch can perform asynchronous operations

Two important small principles:

  1. The functions managed by Vue should be written as ordinary functions, so that the point of this is the vm or component instance object
  2. All functions that are not managed by Vue (timer callback function, ajax callback function, Promise callback function, etc.), filter and are best written as arrow functions, so that the point of this is the vm or component instance object

For example, if an ordinary function is written in the timer function, this points to window

Keywords: Javascript Front-end html server

Added by Craig_H on Wed, 01 Dec 2021 08:24:23 +0200