computed

Computed is a computed attribute, used to compute a value that can be invoked without parentheses and used as a property, and computed shows new computed results that are cached based on dependent data. If a data set depends on other data, design it for computed.

Example:

<div id="example"> 
    <p>Original message: "{{ message }}"</p>
    <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
Copy the code
Var vm = new Vue({el: '#example', data: {message: 'Hello'}, computed: {// Calculate attributes of the getter reversedMessage: Function () {// 'this' points to the vm instance return this.message.split('').reverse().join('')}}})Copy the code

Results:

Original message: “Hello”

Computed reversed message: “olleH”

watch

Watch is a listening attribute that executes a function when the data (attribute) changes, characterized by immediate and deep. If you need to do something when some data changes, use Watch.

  • Grammar 1
Watch :{obj1:function(value,oldValue), // obj2(){}, //ES6 (obj3:[f1,f2], // two functions, In turn perform f1 and f2 obj4: 'methodName', / / the methods inside, looking for corresponding function obj5: {handler: fn, deep: true, immediate: true}, / / {executive function, whether the deep, } obj6:'object.a':function(){}Copy the code
  • Syntax 2
vm.$watch('xxx',fn,{deep:... ,immediate:... }) //' XXX 'can be changed to a function that returns a stringCopy the code

Watch of this

Do not use arrow functions in Watch

const vm = new Vue({
    data: ...
    watch:{
        n:function(){
            this ===vm
        }
    }
})
Copy the code

Here this represents a global variable and new Vue is a function call

immediate

Vue does not execute watch by default for the first rendering. However, Vue provides the immediate method to indicate whether watch should be executed during the first rendering.

Immediate :true/false // Default false This parameter is not executedCopy the code

deep

In Vue data, simple types look at values and complex types (objects) look at addresses. Vue provides a deep method to determine whether to look at changes in attributes in the object.

Deep :true/false // Default falseCopy the code