- Getting Started
- The Vue Instance
- Data Binding Syntax
- Computed Properties
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Methods and Event Handling
- Form Input Bindings
- Reactivity in Depth
- Custom Directives
- Custom Filters
- Building Large-Scale Apps
- Comparison with Other Frameworks
- Join the Vue Community!
In-template expressions are very convenient, but they are really meant for simple operations only. Templates are meant to describe the structure of your view. Putting too much logic into your templates can make them bloated and hard to maintain. This is why Vue.js limits binding expressions to one expression only. For any logic that requires more than one expression, you should use a computed property.
Here we have declared a computed property
b. The function we provided will be used as the getter function for the property
You can open the console and play with the example vm yourself. The value of
vm.b is always dependent on the value of
You can data-bind to computed properties in templates just like a normal property. Vue is aware that
vm.b depends on
vm.a, so it will update any bindings that depends on
vm.a changes. And the best part is that we’ve created this dependency relationship declaratively: the computed getter function is pure and has no side effects, which makes it easy to test and reason about.
Vue.js does provide an API method called
$watch that allows you to observe data changes on a Vue instance. When you have some data that needs to change based on some other data, it is tempting to use
$watch - especially if you are coming from an AngularJS background. However, it is often a better idea to use a computed property rather than an imperative
$watch callback. Consider this example:
The above code is imperative and repetitive. Compare it with a computed property version:
Much better, isn’t it?
Computed properties are by default getter-only, but you can also provide a setter when you need it:
Now when you call
vm.fullName = 'John Doe', the setter will be invoked and
vm.lastName will be updated accordingly.
The technical details behind how computed properties are updated are discussed in another section dedicated to the reactivity system.