Max P.
Max P.

Reputation: 5679

Expressions vs computed properties in templates in Vue.js

What is better to use in templates: expressions or computed properties?

Ex:

<span :class="'static_part' + dynamic_part"></span>
...
data: {
    dynamic_part: 'xxx',
}

or

<span :class="span_class"></span>
...
data: {
    dynamic_part: 'xxx',
},
computed: {
    span_class() {
        return 'static_part' + dynamic_part;
    }
}

1-st way is smaller and easier to understand. But what about performance?

Upvotes: 1

Views: 874

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

According to official docs

In-template expressions are very convenient, but they are meant for simple operations. Putting too much logic in your templates can make them bloated and hard to maintain

and

Instead of a computed property, we can define the same function as a method. For the end result, the two approaches are indeed exactly the same. However, the difference is that computed properties are cached based on their reactive dependencies

I see that using computed property could also separate the logic from the content and help other who will read your code that this properties are calculated and based on other ones

Upvotes: 2

Related Questions