You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: source/guide/computed.md
+28-16Lines changed: 28 additions & 16 deletions
Original file line number
Diff line number
Diff line change
@@ -33,35 +33,47 @@ var demo = new Vue({
33
33
demo.fullName// 'Foo Bar'
34
34
```
35
35
36
+
When you only need the getter, you can provide a single function instead of an object:
37
+
38
+
```js
39
+
// ...
40
+
computed: {
41
+
fullName:function () {
42
+
returnthis.firstName+''+this.lastName
43
+
}
44
+
}
45
+
// ...
46
+
```
47
+
36
48
A computed property is essentially a property defined with getter/setter functions. You can use a computed property just like a normal property, but when you access it, you get the value returned by the getter function; when you change its value, you trigger the setter function passing in the new value as its argument.
37
49
38
50
## Dependency Collection Gotcha
39
51
40
52
Like inline expressions, Vue.js automatically collects dependencies for computed properties and refreshes them when their dependencies change. There's one thing to keep in mind though: since Vue.js collects dependencies by monitoring which properties are accessed inside a getter, you need to be careful when there is conditional logic within your getters. Consider this example:
41
53
42
54
```js
43
-
status: {
44
-
$get:function () {
45
-
returnthis.validated
46
-
?this.okMsg
47
-
:this.errMsg
48
-
}
55
+
// ...
56
+
status:function () {
57
+
returnthis.validated
58
+
?this.okMsg
59
+
:this.errMsg
49
60
}
61
+
// ...
50
62
```
51
63
52
64
If `validated` is true in the beginning, then `errMsg` will not be accessed and therefore not collected as a dependency. Vice-versa for `okMsg`. To get around this you can simply manually access potentially unreachable properties in your getter:
53
65
54
-
```
55
-
status: {
56
-
$get: function () {
57
-
// access dependencies explicitly
58
-
this.okMsg
59
-
this.errMsg
60
-
return this.validated
61
-
? this.okMsg
62
-
: this.errMsg
63
-
}
66
+
```js
67
+
// ...
68
+
status:function () {
69
+
// access dependencies explicitly
70
+
this.okMsg
71
+
this.errMsg
72
+
returnthis.validated
73
+
?this.okMsg
74
+
:this.errMsg
64
75
}
76
+
// ...
65
77
```
66
78
67
79
<pclass="tip">You don't need to worry about this in inline expressions because Vue.js' expression parser takes care of it for you.</p>
0 commit comments