目录

Computed Attributes

Use Instructions

Using expressions properly in a template can help improve development efficiency. However, including too much processing logic in a template can make the template cumbersome and difficult to maintain. Example:

<text>{{ message.split('').reverse().join('') }} </text>

Here, the template no longer implements a simple declarative logic. If expressions as such are used extensively, they would harm the readability of the template. In addition, using the same expression repeatedly may complicate the code, making it difficult to maintain. As an alternative, you can use computed attributes as follows.

<div>
    <text>Original message: "{{ message }}"</text>
    <text>Comtextuted reversed message: "{{ reversedMessage }}"</text>
</div>
export default {
    data: {
        message: 'Hello'
    },
    computed: {
        // Calculate the getter of the attribute.
        reversedMessage() {
            // this points to the VM instance.
            return this.message.split('').reverse().join('')
        }
    },
    onReady() {
        console.log(this.reversedMessage) // olleH
        this.message = 'Goodbye'
        console.log(this.reversedMessage) // eybdooG
    }
}

In the preceding code, the computed attribute reversedMessage is declared. It is used as the getter function of the vm.reversedMessage attribute. In this case, the value of vm.reversedMessage will always depend on the value of vm.message.

During coding, you can bind a computed attribute to a template in the same way as binding a common attribute. After successful binding, the component instance will learn that vm.reversedMessage depends on vm.message, and all data that depends on vm.reversedMessage will be updated whenever vm.message changes.

Setting the setter Function

By default, a computed attribute only provides the getter function. If necessary, it can provide an addition setter function.

export default {
    data: {
        firstName: 'Quick',
        lastName: 'App'
    },
    computed: {
        fullName: {
            get() {
                return `${this.firstName} ${this.lastName}`
            },
            set(value) {
                const names = value.split(' ')
                this.firstName = names[0]
                this.lastName = names[names.length - 1]
            }
        }
    },
    onReady() {
        console.log(this.fullName) // Quick app
        this.fullName = 'John Doe'
        console.log(this.firstName) // John
        console.log(this.lastName) // Doe
    }
}

Caching Results Returned by Computed Attributes

You can also call a method in an expression to achieve the same effect.

<text>Reversed message: "{{ reversedMessage() }}"</text>
// In the component:
export default {
    data: {
        message: 'Hello'
    },
    reversedMessage () {
        return this.message.split('').reverse().join('')
    }
}

A function can be defined as a method rather than a computed attribute. When defined as a method, the function can deliver the same result as when it is defined as a computed attribute. However, the difference is that computed attributes have their calculation results cached based on their dependencies. Calculation is performed again only when the related dependencies change. In the preceding example, as long as the message stays unchanged, the computed attribute reversedMessage will immediately return the previous calculation result whenever it is accessed, without having to execute the getter function again.

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

computed: {
    now () {
        return Date.now()
    }
}

In contrast, when a method rather than a computed attribute is used, the function is always executed whenever the method is called.

Why is caching needed? Assume that computed attribute A is performance-consuming, as it needs to traverse a huge array and do a lot of computations. In addition, other computed attributes may depend on A. Without caching the calculation result of A, the getter function of A will have to be executed a number of times. However, if you do not want to cache the calculation result, use a method instead.

Links

[h2]FAQ

How Can I Specify the Element Style by Using Computed Attributes?