“This is the 17th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge in 2021”.

1. Calculate attributes

1. Basic usage

For some complex logical computations, Vue provides calculation attributes. Here is a simple example:

<div id="root">Number 1:<button @click="add(1)">add</button>
    <button @click="min(1)">Reduction of</button>
    <br />Number 2:<button @click="add(0)">add</button>
    <button @click="min(0)">Reduction of</button>
    <h3>{{num1}}+{{num2}}={{sum}}</h3>
</div>
Copy the code
const vm = new Vue({
    el: '#root'.data: {
        num1: 2.num2: 3,},methods: {
        add(flag) {
            if (flag) {
                this.num1++;
            } else {
                this.num2++; }},min(flag) {
            if (flag) {
                this.num1--;
            } else {
                this.num2--; }}},computed: {
        sum: {
            get() {
                return this.num1 + this.num2;
            },
            set(value) {
                console.log('Set called');
                this.num1 = 0;
                this.num2 = value - this.num1; }},}});Copy the code

This code defines the calculation property sum, which is the sum of num1 and num2 in data.

  • The first time I read it,sumIn thegetterWill be called and return the value assumThe value of the.
  • When the dependent data changes,sumIn thegetterWill also be called, return the value assumThe value of the.
  • When modifyingsumWhen,sumIn thesetterWill be called.

2. Short form

If you do not use setter functions, you can abbreviate the method name sum as the calculated property name and the function as the original getter function.

computed: {
    sum() {
        return this.num1 + this.num2; }},Copy the code

3. The cache

Computed properties are cached based on their reactive dependencies. They are reevaluated only when the associated reactive dependencies change. This means that as long as num1 and num2 have not changed and sum is accessed multiple times, the computed property will immediately return the computed result without having to execute the function again.

This also means that the following computed attributes will not be updated because date.now () is not a reactive dependency:

computed: {
    now() {
        return Date.now(); }},Copy the code

2. The listener

1. Basic usage

<div id="root">
	<h2>Current mode: {{mode}}</h2>
	<button @click="changeMode">Switch mode</button>
</div>
Copy the code
const vm = new Vue({
	el: '#root'.data: {
		isDark: true.mode: 'Dark Mode',},methods: {
		changeMode() {
			this.isDark = !this.isDark; }},watch: {
		isDark: {
			// Call handler once during initialization
			immediate: true.// When is the handler called? When isDark changes.
			handler(newValue, oldValue) {
				console.log(newValue, oldValue);
				this.mode = this.isDark ? 'Dark Mode' : 'Day mode'; }},}});Copy the code

Defines a listener that listens for isDark properties and calls handler functions when isDark changes.

Add immediate: true so that Vue initialization automatically calls the handler function once.

Listeners are useful when you need to perform asynchronous or expensive operations when data changes.

2. Another way to write it

Define a listener on the sample object VM.

vm.$watch('isDark', {
	// Call handler once during initialization
	immediate: true.handler(newValue, oldValue) {
		console.log(newValue, oldValue);
		this.mode = this.isDark ? 'Dark Mode' : 'Day mode'; }});Copy the code

3. Deep monitoring

By default, the watch in Vue does not detect changes in the internal value of an object. This does not mean that Vue cannot detect changes in the internal value of an object.

Configure deep:true to detect changes in the object’s internal values.

watch: {
    obj: {
        immediate: true.deep: true.// Enable depth monitoring
        handler(newValue, oldValue){},}},Copy the code

4. Short form

watch: {
    isDark(newValue, oldValue){}},Copy the code
vm.$watch('isDark'.(newValue, oldValue) = > {});
Copy the code