From 1ba69e7b7c12ea4fd6da34bff15b03257d9dac3a Mon Sep 17 00:00:00 2001 From: Jun Shindo <46585162+jay-es@users.noreply.github.com> Date: Mon, 30 Sep 2024 20:41:09 +0900 Subject: [PATCH] feat(guide/computed): add previous to computed --- 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 be7a0c11c..d35fe6767 100644 --- a/src/guide/essentials/computed.md +++ b/src/guide/essentials/computed.md @@ -259,6 +259,115 @@ const fullName = computed({ +## 前回の値を取得する {#previous} + +- 3.4 以上でのみサポートされています + + +必要であれば、ゲッターの第 1 引数にアクセスすることで、算出プロパティが前回返した値を取得できます: + +
+ +```js +export default { + data() { + return { + count: 2 + } + }, + computed: { + // この computed は、count が 3 以下の場合にはその値を返します。 + // count が >= 4 の場合は、count が 3 以下になるまで、 + // 条件を満たした最後の値が代わりに返されます + alwaysSmall(previous) { + if (this.count <= 3) { + return this.count; + } + + return previous; + } + } +} +``` +
+ +
+ +```vue + +``` +
+ +書き込み可能な 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} ### getter 関数は副作用のないものでなければならない {#getters-should-be-side-effect-free}