Differences among calculated, Methods and Watch in vue

1. Calculated attribute

It is very convenient to use js expressions in the template. The purpose of the design is only for simple operation. Putting too much logic in the template will make the template too heavy and difficult to maintain. Therefore, for any complex logic, you should use computational properties.

<!-- Complex operation -->
<div>{{message.split('').reverse().join('')}}</div>
<!-- Computing attributes instead of complex operations -->
<div>{{reverseMessage}}</div>
computed: {
    <!-- Calculation of attributes getter -->
    reverseMessage: function () {
        return this.message.split('').reverse().join('');
    }
}

2 . Comparison between calculated and methods

We can use methods to achieve the same effect as calculating attributes

<!--HTML part-->
<div id="app">
    <h1>{{message}}</h1>
    <p class="test1">{{methodTest}}</p>
    <p class="test2-1">{{methodTest()}}</p>
    <p class="test2-2">{{methodTest()}}</p>
    <p class="test2-3">{{methodTest()}}</p>
    <p class="test3-1">{{computedTest}}</p>
    <p class="test3-2">{{computedTest}}</p>
</div>

<!--script part-->
let vm = new Vue({
    el: '#app',
    data: {
        message: 'I'm the news,'
    },
    methods: {
        methodTest() {
            return this.message + 'Now I use methods'
        }
    },
    computed: {
        computedTest() {
            return this.message + 'Now I use computed'
        }
    }
})

In the official document, the two most important differences between calculated and method are emphasized:

1 . computed is a property call and methods is a function call
2 . computed has the function of caching, while methods will not be cached

Property call:
1 . The method defined by computed is called in the form of attribute access, {computedTest}}
2 . For the methods defined by methods, we must add () to call, {methodTest()}}
Cache function:
The calculation attribute has a cache: it will be recalculated only when the attribute on which the calculation attribute depends changes
methods are not cached: the method recalculates the results every time.
Cache benefits:
Compared with what we all know, the core function of HTTP cache is to reuse some resources that have not been updated on the server, avoid some unnecessary requests and optimize the user experience
The same is true for computed:
In the above example, the methods defined by methods are accessed in the form of function calls. Test2-1, test2-2 and test2-3 repeatedly run the methodTest method three times. If we encounter a scenario that requires 1000 return values of methodTest, there is no doubt that this is bound to cause a lot of waste
What's more, if you change the value of message, each of the 1000 methodTest methods will recalculate....

That's why the official documentation repeatedly emphasizes that you should use computational properties for any complex logic

computed Depend on data The data in is changed only when it depends on the data` `Time computd Property will be recalculated

As the above example, in Vue When instantiating, the computedTest method will perform a calculation and return a value. In subsequent code writing, the computedTest method will not recalculate as long as the message data that the computedTest method depends on does not change, that is, test3-1 and test3-2 directly get the return value, not the result of recalculation by the computedTest method.

This benefit is also obvious. Similarly, if we encounter a scenario that requires 1000 computedTest return values, there is no doubt that this will greatly save memory compared with methods
Even if you change the value of message, computedTest will only calculate it once.
remarks:
1 . computed can be accessed as either a property or a method
2 . Another important reason for the origin of computed is to prevent excessive logic in text interpolation, which makes it difficult to maintain

watch

  • watch
    Vue's watch property can be used to listen for data changes in the data property
   <div id="app">
      <input type="text" v-model="firstname" />
    </div>
    <script type="text/javascript">
      var vm = new Vue({
        el:"#app",
        data:{
          firstname:"",
          lastname:""
        },
        methods:{},
        watch:{
          firstname:function(){
            console.log(this.firstname)
          }
        }
      })
    </script>

It can be learned from the above code that the console will print as many times as the value in the input box changes

At the same time, you can also directly use parameters in the monitored function to obtain new and old values

watch:{
          firstname:function(newValue,OldValue){
            console.log(newValue);
            console.log(OldValue);
          }
        }

The first parameter is the new value and the second parameter is the old value

At the same time, Watch can also be used to monitor the changes of routing router, but the monitoring elements here are fixed

    <div id="app">
      <!--
        because Vue-router of hash Matching principle, so we need to add one to the original defined path#number
      -->
<!--  <a href="#/Login "rel =" external nofollow "> login</a>
      <a href="#/Register "rel =" external nofollow "> register < / a > -- >
      <router-link to="/login" tag="span">Sign in</router-link>
      <router-link to="/register">register</router-link>
      <router-view></router-view>
    </div>
  </body>
  <script>
    var login={
      template:'<h1>Login component</h1>'
    }
    var register={
      template:'<h1>Register components</h1>'
    }
    var routerObj = new VueRouter({
      routes:[
      //The component here can only use the component object, not the name of the registered template
        {path:"/login",component:login},
        {path:"/register",component:register}
      ]
    })
    var vm = new Vue({
      el:'#app',
      data:{
      },
      methods:{
         
      },
      router:routerObj,//Register the routing rule object on the VM instance
      watch:{
        '$route.path':function(newValue,OldValue){
            console.log(newValue);
            console.log(OldValue);
        }
      }
    })
  </script>

watch is to observe the change of an attribute and recalculate the attribute value. computed is to recalculate the attribute value through the change of the dependent attribute. Insert code slice here
In most cases, there is little difference between watch and computed. However, if you want to perform asynchronous operations while data changes or have a large overhead, watch is the best choice.

Methods, watch and computed

1 . The results of the computed attribute are cached and will not be recalculated unless the dependent responsive attribute changes. It is mainly used as an attribute;
2 . The methods method represents a specific operation, mainly writing business logic;
3 . watch is an object. The key is the expression to be observed, and the value is the corresponding callback function. It is mainly used to monitor the changes of some specific data, so as to carry out some specific business logic operations; It can be regarded as a combination of computed and methods;

Calculate getter s and setters of attributes

The default calculation property is only get, and the set method can be set when necessary

fullName: {
    get: function () {
        return this.firstName + " " + this.lastName;
    },
    set: function (val) {
        this.firstName = val.split(' ')[0];
        this.lastName = val.split(' ')[1];
    }
}

Keywords: Javascript Front-end Vue Vue.js

Added by KPH71 on Thu, 10 Feb 2022 23:53:53 +0200