Watch and computed are monitoring data

   new Vue({
            el:'#app'.template:` < div > 1. {{MSG}} | | {{data1}} {{data2}} < br / > 2. {{fullName}} < button @ click = "changed (123)" > point I trigger < / button > < / div > `.watch: {msg(value){ (MSG (new,old)); (MSG (new,old)); (MSG (new,old)
                    this.data1 = value + this.data1;
                    this.data2 = value + this.data2
                },
                $route(to,from) {$route = $route = $route = $route = $route = $route = $route = $route}},computed: {fullName(){
                    return  this.firstName  + "" +this.lastName; }},methods: {changed(a){
                    this.msg = 6868 + a;
                    this.firstName = 'wang'; }},data(){
                return{
                    msg:123.data1:'wshi1'.data2:'wshi2'.firstName:"ZHOU".lastName:"wang",}}})Copy the code

Click on the formerAfter clicking onBoth Watch and computed listen to data only when it changes, but they are good at different thingsWatch is better at one-to-many: is to listen for a single data that can affect multiple dataComputed is good at many-to-one: Mainly monitors multiple data that affects one data. The data generated by a return must be automatically defined without being defined again in data. Of course, you can also use Watch to monitor every data that constitutes computed data monitored, but the code repetition rate is too high

The difference between Methods, Watch and computed

This is straightforward. Methods execute functions passively through event-driven, and computed executes functions actively when monitored data changes

The difference between methods and computed

The difference between active and passive is that methods are not cached, and computed operations are cached (as long as the data on which the operation depends does not change, the results are extracted from the cache).

 new Vue({
            el: '#app'./ / set two button, click on the call getMethodsDate respectively, getComputedDate method
            template: ` 
      
`
.methods: { getMethodsDate() { alert(new Date()},// Returns the computed property set in the computed option -- computedDate getComputedDate() { alert(this.computedDate) // Pop computedDate inside}},computed: { computedDate: function () { return new Date()}}})Copy the code

Click methods for the first time The second point is methods The time displayed above is different, it will re-new Date() is not the same as normalClick computed for the first time Click computed the second time This is because the new Date() that this function relies on was created when the Created () life cycle was triggered and will not be new again, so the same value appears twice when clicked