Properly use computed properties and watch in Vue;

What are calculated attributes:

Calculated properties can be understood as: can be used to write some logical properties;Copy the code

Function:

1. Usually used to reduce the calculation logic in the template; 2. Help us to do some data caching; When our dependency data is unchanged, no logical code is executed; When the logical computation is more complex, it can help us to provide performance; Because it only computes if it depends on changes in the data; 3. Rely on fixed data types (reactive data types)Copy the code

Reference teacher Tang’s example code: Through breakpoint code, understand computed properties computed:

In the following computed. Initialize message in data; Force refresh by clicking button and executing this.$forceUpdate(); We can find:

The log of the logical code in the calculated property reversedMessage1; And there are updates; The log of the logical code in reversedMessage2 is always printed; That’s the advantage of using computed attributes;

<template> <div> <p>Reversed message1: "{{ reversedMessage1 }}"</p> <p>Reversed message2: "{{ reversedMessage2() }}"</p> <p>{{ now }}</p> <button @click="() => $forceUpdate()">forceUpdate</button> <br /> <input  v-model="message" /> </div> </template> <script> export default { data() { return { message: "hello vue" }; }, computed: {// Calculate getter reversedMessage1: function() {console.log(" Execute reversedMessage1"); return this.message .split("") .reverse() .join(""); }, now: function() { return Date.now(); }}, methods: {reversedMessage2: function() {console.log(" execute reversedMessage2"); return this.message .split("") .reverse() .join(""); }}}; </script>Copy the code

What is a listener watch?

** listener ** : can listen to any data; When the data changes, execute some logical code; In Watch, you can perform any code logic, such as function throttling, ajax asynchronously fetching data; Even manipulating Dom;Copy the code

What listeners do: More flexible and versatile;

To quote Tang’s code example: Understanding listeners through code:

In the watch.vue code example,

  1. Reference all data in the {{}} template with $data;

  2. Change the value of A by button;

  3. In Watch, by monitoring multi-layer nested data, the corresponding logic code is executed when A changes.

  4. In e, perform deep listening, deep:true; Whenever any data in e: changes, whether f or g, e’s handler function is executed;

Computed properties computed VS listener watch;

Watch can do everything computed, but not vice versa; Use computed as much as you can do with it;

Understand both in code:

ComputedFullName. The vue; By calculating the attribute fullName; Only a piece of logical code is needed to complete the Fullname listening;

<template> <div> {{ fullName }} <div>firstName: <input v-model="firstName" /></div> <div>lastName: <input v-model="lastName" /></div> </div> </template> <script> export default { data: function() { return { firstName: "Foo", lastName: "Bar" }; }, computed: { fullName: function() { return this.firstName + " " + this.lastName; } }, watch: { fullName: function(val, oldVal) { console.log("new: %s, old: %s", val, oldVal); }}}; </script>Copy the code

WatchFullName. The vue; Display fullName change needs; Listen on firstName and lastName; Execute two pieces of logic code respectively;

<template> <div> {{ fullName }} <div>firstName: <input v-model="firstName" /></div> <div>lastName: <input v-model="lastName" /></div> </div> </template> <script> export default { data: function() { return { firstName: "Foo", lastName: "Bar", fullName: "Foo Bar" }; }, watch: { firstName: function(val) { this.fullName = val + " " + this.lastName; }, lastName: function(val) { this.fullName = this.firstName + " " + val; }}}; </script>Copy the code

In this case, in terms of the amount of code, it’s much simpler to compute properties using computed data; What you can do with computed you can do with the watch property;

** Extension: ** Update the watchFullName. Vue file until the user enters more than 500 ms.

** Analysis: ** It can be seen from code analysis that the anti-shake strategy:

By clearTimeout(timer); let timer=setTimeout(()=>{}); When the user keeps inputting new data, the current timer is cleared. If there is no new data update for the listening dependent data within 500ms, the setTimeout(()=>{}) callback function is executed.

<template> <div> {{ fullName }} <div>firstName: <input v-model="firstName" /></div> <div>lastName: <input v-model="lastName" /></div> </div> </template> <script> export default { data: function() { return { firstName: "Foo", lastName: "Bar", fullName: "Foo Bar" }; }, watch: { firstName: function(val) { clearTimeout(this.firstTimeout); this.firstTimeout = setTimeout(() => { this.fullName = val + " " + this.lastName; }, 500); }, lastName: function(val) { clearTimeout(this.lastTimeout); this.lastTimeout = setTimeout(() => { this.fullName = this.firstName + " " + val; }, 500); }}}; </script>Copy the code