Computing properties is an important part of Vue components. It has functions such as separating logic, caching values, and bidirectional binding.

The separation of logic

Requirements are as follows:

// Given the text text, remove the white space at the beginning and end, and then invert it. // example: const text = 'float float' // ==> float float float float float float float floatCopy the code

Instead of using computed attributes, the code looks like this:

<template> <div id="example"> {{ text.split('').reverse().join('') }} </div> </template> <script> export default { data: </script> () => ({text: 'flowers, flowers, flowers'})} </script>Copy the code

Using computed attributes, the code looks like this:

<template> <div id="example"> {{ normalizedText }} </div> </template> <script> export default { data: () => ({ text: 'All over the world'}), computed: {normalizedText() {return this.text.split('').reverse().join('')}} </script>Copy the code

Obviously, with computed attributes, the template is cleaner with the associated logic in computed options:

The cache value

Following the example, if we do not change the value of text, normalizedText will not recalculate, that is, normalizedText will cache its evaluation results until its dependency on text changes. We can test this:

Two-way binding

We can implement bidirectional data binding using getters and setters for computed properties: