From 4567e55ee0641e0a9501f89621c1e641cb6cec25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= Date: Fri, 27 Sep 2024 18:20:22 +0200 Subject: [PATCH] feat(guide/computed): add previous to computed (#3001) * feat(guide/computed): add previous to computed Signed-off-by: GitHub * fix: replace badge with list item * refactor: address review comments * Update src/guide/essentials/computed.md * Update src/guide/essentials/computed.md --------- Signed-off-by: GitHub Co-authored-by: Natalia Tepluhina --- src/guide/essentials/computed.md | 109 +++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/src/guide/essentials/computed.md b/src/guide/essentials/computed.md index 60055f06fc..335ec34d05 100644 --- a/src/guide/essentials/computed.md +++ b/src/guide/essentials/computed.md @@ -259,6 +259,115 @@ Now when you run `fullName.value = 'John Doe'`, the setter will be invoked and ` +## Getting the previous value {#previous} + +- Only supported in 3.4+ + +In case you need it, you can get the previous value returned by the computed property accessing +the first argument of the getter: + +
+ +```js +export default { + data() { + return { + count: 2 + } + }, + computed: { + // This computed will return the value of count when it's less or equal to 3. + // When count is >=4, the last value that fulfilled our condition will be returned + // instead until count is less or equal to 3 + alwaysSmall(previous) { + if (this.count <= 3) { + return this.count; + } + + return previous; + } + } +} +``` +
+ +
+ +```vue + +``` +
+ +In case you're using a writable computed: + +
+ +```js +export default { + data() { + return { + count: 2 + } + }, + computed: { + alwaysSmall: { + get(previous) { + if (this.count <= 3) { + return this.count; + } + + return previous; + }, + set(newValue) { + this.count = newValue * 2; + } + } + } +} +``` + +
+
+ +```vue + +``` + +
+ + ## Best Practices {#best-practices} ### Getters should be side-effect free {#getters-should-be-side-effect-free}