Earlier we talked about filters, and we said at the beginning that VUe3 no longer supports them, so here we can completely replace them with computed attributes, which is why VUe3 chose to get rid of filters (for simplicity).

Computed properties

Similarly, as the name implies, as the front-end framework developed by the People indeed words are more image, the calculation of attributes is to do the calculation of variables, we obtain the calculated attributes through the calculation of attributes, can be string processing, but also can be the operation of numbers and so on. By calculating attributes, we can simplify data operation in interpolation and simplify component structure.

Features of calculated properties: split logic, cached values, bidirectional binding.

Use computed (Simple)

We add a function with a return value to the evaluated property, where the function name can be called as a variable, that is, without the () operator.

        <div>{{num1}}-{{num2}}-{{sum}}</div>
Copy the code
.computed: {sum(){
                    return this.num1+this.num2
                }
            }
......
Copy the code

If we execute: sum(‘1’) as a function, an error is reported, and the evaluated attribute is not allowed as a function.

Expand Use Computed

Computed attributes support not only filtered returns of variables, but also the inclusion of both GET and SET.

<div>{{summ}}-{{sum2}}</div>
Copy the code
.sum2: {
                    get: function () {
                        return this.summ+1
                    },
                    set: function (v) {
                        this.summ = v*1}}...Copy the code

The second is not very common, and you’ll notice the difference: the former is read-only, while the latter is read-write. The former is a read-only function, while the latter is an object containing set and GET methods.

Important differences between computed properties and methods

  • Direct difference:

    Using computed attributes in interpolation or V-instructions without () and using methods can achieve the same effect. The calculation property has the calculation cache mechanism. When the virtual DOM changes and the real DOM is updated, all methods are repeatedly executed. However, the calculation property will monitor the variables that directly affect the returned value of the calculation, and the calculation property will be recalculated only when the variable changes, otherwise the calculation result in the cache will be read for output. This reduces costs, but is prone to structural bugs.