Vue. js computing attributes computed and $ watch, vue. jscomputed
Binding expressions in a template is very convenient, but they are only used for simple operations. The template is used to describe the view structure. Adding too many logic in the template will make the template too heavy and difficult to maintain. This is why Vue. js limits the binding expression to one. If you need more than one expression logic, you should use ** calculation attribute **.
Basic example
<div id="example"> a={{ a }}, b={{ b }}</div>
Var vm = new Vue ({el: '# example', data: {a: 1}, computed: {// getter B: function () of a computing attribute () {// 'eas' points to the vm instance return this. a + 1 }}})
Here we declare a computing attribute B. The function we provide will be used as the getter for attributes vm. B.
console.log(vm.b) // -> 2vm.a = 2console.log(vm.b) // -> 3
You can open the browser console and modify the vm. The value of vm. B always depends on the value of vm..
You can bind a computing property to a template just like binding a common property. Vue knows that vm. B Depends on vm. a, so when vm. a changes, the binding dependent on vm. B will also be updated. The best thing is that we create this dependency in a declarative manner: The getter of the calculation attribute is clean and has no side effects, so it is easy to test and understand.
Calculation attribute vs. $ watch
Vue. js provides the $ watch method, which is used to observe data changes on Vue instances. $ Watch is attractive when some data needs to be changed based on other data-especially if you are from AngularJS. However, it is usually better to use a calculated attribute instead of an imperative $ watch callback. Consider the following example:
<div id="demo">{{fullName}}</div>var vm = new Vue({ el: '#demo', data: { firstName: 'Foo', lastName: 'Bar', fullName: 'Foo Bar' }})vm.$watch('firstName', function (val) { this.fullName = val + ' ' + this.lastName})vm.$watch('lastName', function (val) { this.fullName = this.firstName + ' ' + val})
The above code is imperative. Comparison with computing attributes:
var vm = new Vue({ data: { firstName: 'Foo', lastName: 'Bar' }, computed: { fullName: function () { return this.firstName + ' ' + this.lastName } }})
This is better, isn't it?
Setter Calculation
The calculation attribute is getter by default, but you can also provide a setter when needed:
// ...computed: { fullName: { // getter get: function () { return this.firstName + ' ' + this.lastName }, // setter set: function (newValue) { var names = newValue.split(' ') this.firstName = names[0] this.lastName = names[names.length - 1] } }}// ...
Now, when vm. fullName = 'John Doe 'is called, setter is called, and vm. firstName and vm. lastName are updated accordingly.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.