Vue.js Computed Properties

Computed Properties Keyword:computed。

Computed properties are very useful when dealing with some complex logic.

You can look at the following example of reversing a string:

Example 1

<div id="app"> {{ message.split('').reverse().join('') }} </div>

Try it Yourself »

In Example 1, the template becomes very complex and is not easy to read and understand.

Next, let's look at an example that uses computed properties:

Example 2

<div id="app"> <p>Original string: {{ message }}</p> <p>Reversed string after computation: {{ reversedMessage }}</p> </div> <script>var vm = new Vue({ el: '#app', data: { message: 'Example!' }, computed: { // Getter for the computed property reversedMessage: function () { // `this` points to the vm instance return this.message.split('').reverse().join('') } } })</script>

Try it Yourself »

In Example 2, a computed property named reversedMessage is declared.

The provided function will be used as the getter for the property vm.reversedMessage.

vm.reversedMessage depends on vm.message. When vm.message changes, vm.reversedMessage will also update.


computed vs methods

We can use methods instead of computed. The effect of the two is the same, but computed is cached based on its dependencies, and only re-evaluates when the related dependencies change. When using methods, the function will always be called and executed again on re-rendering.

Example 3

methods: { reversedMessage2: function () { return this.message.split('').reverse().join('') } }

Try it Yourself »

It can be said that using computed gives better performance, but if you don't want caching, you can use the methods property.


computed setter

A computed property only has a getter by default, but you can also provide a setter when needed:

Example 4

var vm = new Vue({ el: '#app', data: { name: 'Google', url: 'http://www.google.com' }, computed: { site: { // getter get: function () { return this.name + ' ' + this.url }, // setter set: function (newValue) { var names = newValue.split(' ') this.name = names[0] this.url = names[names.length - 1] } } } }) //When the setter is called, vm.name and vm.url will also be updated accordingly. vm.site = 'Example http://www.example.com'; document.write('name: ' + vm.name); document.write('<br>'); document.write('url: ' + vm.url);

Try it Yourself »

From the example's running result, when vm.site = 'Example http://www.example.com'; is executed, the setter will be called, and vm.name and vm.url will also be updated accordingly.

Other Extensions