Computed(Calculated attributes)

The calculated property is recalculated when the value of its dependent property changes, otherwise the property value in the cache is used.

Calculation functions, complex calculations should be placed here, try not to directly calculate in the template syntax, the calculated value here is dynamic change, that is, if one of the calculated values changes, the final result will also change

Let’s go straight to the example:

Vue import Vue from "Vue /dist/vue.js"; Vue.config.productionTip = false; new Vue({ data() { return { num1: 10, num2: 20, nums: 5 }; }, computed: { addNum: { get() { return Number(this.nums) + Number(this.num1) + Number(this.num2); }, set(value) { console.log(value); }}} template: ` < div > / / here is calculated addNum {{addNum}} < / div > < / div > `, the methods: {}}) $mount (" # app ");Copy the code

This code uses computed. If there is a lot of computation in the code. You can put it in computed so that your code doesn’t look messy, so that the logic of your code looks clearer, and if you change the value in it, it automatically updates.

Can’t you see it clearly?

Vue import {has} from "core-js/core/dict"; import Vue from "vue/dist/vue.js"; Vue.config.productionTip = false; let id = 0; const createUser = (name, gender) => { id += 1; return { id, name, gender }; }; new Vue({ data() { return { users: [createUser (" all ", "male"), createUser (" yuan yuan ", "female"), createUser (" small new ", "male"), createUser (" little kwai ", "female")], gender: ""}; }, computed:{displayUsers(){const hash = {male:' male ', female: 'female'} const {users,gender}= this; if (gender === '') { return this.users }else if (typeof gender === string){ return this.users.filter(u=>u.gender === hash[gender]); }}}, methods:{setGender(string){this.gender = string}}, // How to add event handlers to three buttons // Use computed template: '<div> <div> < button@click ="setGender(')"> All </ button@click ="setGender('male')"> male </ button@click ="setGender('male')" @ click = "setGender (' female ')" > women < / button > < / div > < ul > < li v - for = "u in displayUsers:" key = "u.i d" > {{u.n ame}} - {{u.g ender}} </li> </ul> </div> ` }).$mount("#app");Copy the code

Computed here is a slightly larger computation. As you can see, we have a gender judgment in there. After getting the gender, it will be filtered, and yes, the same gender information will appear when the button is clicked.

Pay attention to

Computed is cached, that is, technical attributes do not count again if the dependent attributes do not change.

Let’s look at the example above. As we click all, male, female. It does it, but if we click on a single button in a row, it doesn’t do it every time, it just does it once.

Getter I setters are not cached by default, Vue does something special.

Watch (listen)

The official documentation

Purpose: The user performs a function when the data changes.

Vue import Vue from "Vue /dist/vue.js"; Vue.config.productionTip = false; new Vue({ data: { n: 0, history: [], inUndoMode: false }, watch: { n: function(newValue, oldValue) { console.log(this.inUndoMode); if (! this.inUndoMode) { this.history.push({ from: oldValue, to: newValue }); }}}, // Better to use computed displayName template: ` <div> {{n}} <hr /> <button @click="add1">+1</button> <button @click="add2">+2</button> <button @ click = "minus1" > 1 < / button > < button @ click = "minus2" > 2 < / button > < hr / > < button @ click = "undo" > cancel < / button > < hr / > {{history}} </div> `, methods: { add1() { this.n += 1; }, add2() { this.n += 2; }, minus1() { this.n -= 1; }, minus2() { this.n -= 2; }, undo() { const last = this.history.pop(); this.inUndoMode = true; console.log("ha" + this.inUndoMode); const old = last.from; this.n = old; $nextTick(() => {this.inundomode = false; }); } } }).$mount("#app");Copy the code

The whole code is done. When we add or subtract a number, Watch listens for that action and records it.

The Watch can also simulate computations. Code examples.

What is change

Let’s just look at the code

Import Vue from "Vue /dist/ Vue. Js "; Vue.config.productionTip = false; new Vue({ data: { n: 0, obj: { a: "a" } }, template: ` <div> <button @click="n += 1">n+1</button> <button @click="obj.a += 'hi'">obj.a + 'hi'</button> <button @click="obj = {a: 'a'} "> object obj = new < / button > < / div > `, watch: {n () {the console. The log (changed" n "); }, obj() {console.log("obj changed "); Obj}, "a" : the function () {the console. The log (" obj. A changed "); } } }).$mount("#app");Copy the code

When we click the button, we can see who has actually changed. For example, when we click the first button, it will look like this:

It says n has changed.

Here comes the conclusion:

  • If YOU change a simple data type that’s up heren += 1Then he has changed.
  • If you change the value of an attribute in an object. That isobj.a += 'hi. The value inside the object changes, but the object does not change, because the object stores a fixed address.
  • If the address changes then the object changes.

If we want the value obj. A in the object to change, tell the object obj that you have changed too.

You can use deep:true

Watch: {n() {console.log("n changed "); }, obj: {handler(){console.log("obj changed "); }, deep:true }, }Copy the code

So we get:

If OBj. A changes, does obj also change

  • The answer, if you need it, is “Changed too.”

    Then use deep: true

  • The answer, if you need it, is “no change.”

    Then use deep:false

  • Deep means whether an object is looking deep when listening for it

You can’t use arrow functions after watch. This points to global objects

The difference between computed and Watch

Computed means calculating attributes.

Computed is to calculate a property, so you don’t need parentheses to call it.

Second, he will cache automatically based on the dependency, and if the dependency doesn’t change, he won’t recalculate.

Watch means to listen.

If a property changes we execute a function.

Asynchronous supported

Watch has two options.

  • One isimmediate: indicates whether the function is executed on the first render.
  • 2 isdeep: If we are listening to an object, whether to look at the changes in the object.

Source: Hungry Man Valley

This article is the original article, the copyright belongs to myself and hunrengu, must indicate the source of reprint