Skip to content

Commit 1ba69e7

Browse files
committed
feat(guide/computed): add previous to computed
1 parent 2d05e3d commit 1ba69e7

File tree

1 file changed

+109
-0
lines changed

1 file changed

+109
-0
lines changed

src/guide/essentials/computed.md

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,115 @@ const fullName = computed({
259259

260260
</div>
261261

262+
## 前回の値を取得する {#previous}
263+
264+
- 3.4 以上でのみサポートされています
265+
266+
267+
必要であれば、ゲッターの第 1 引数にアクセスすることで、算出プロパティが前回返した値を取得できます:
268+
269+
<div class="options-api">
270+
271+
```js
272+
export default {
273+
data() {
274+
return {
275+
count: 2
276+
}
277+
},
278+
computed: {
279+
// この computed は、count が 3 以下の場合にはその値を返します。
280+
// count が >= 4 の場合は、count が 3 以下になるまで、
281+
// 条件を満たした最後の値が代わりに返されます
282+
alwaysSmall(previous) {
283+
if (this.count <= 3) {
284+
return this.count;
285+
}
286+
287+
return previous;
288+
}
289+
}
290+
}
291+
```
292+
</div>
293+
294+
<div class="composition-api">
295+
296+
```vue
297+
<script setup>
298+
import { ref, computed } from 'vue'
299+
300+
const count = ref(2)
301+
302+
// この computed は、count が 3 以下の場合にはその値を返します。
303+
// count が >= 4 の場合は、count が 3 以下になるまで、
304+
// 条件を満たした最後の値が代わりに返されます
305+
const alwaysSmall = computed((previous) => {
306+
if (count.value <= 3) {
307+
return count.value;
308+
}
309+
310+
return previous;
311+
})
312+
</script>
313+
```
314+
</div>
315+
316+
書き込み可能な computed を使用している場合は:
317+
318+
<div class="options-api">
319+
320+
```js
321+
export default {
322+
data() {
323+
return {
324+
count: 2
325+
}
326+
},
327+
computed: {
328+
alwaysSmall: {
329+
get(previous) {
330+
if (this.count <= 3) {
331+
return this.count;
332+
}
333+
334+
return previous;
335+
},
336+
set(newValue) {
337+
this.count = newValue * 2;
338+
}
339+
}
340+
}
341+
}
342+
```
343+
344+
</div>
345+
<div class="composition-api">
346+
347+
```vue
348+
<script setup>
349+
import { ref, computed } from 'vue'
350+
351+
const count = ref(2)
352+
353+
const alwaysSmall = computed({
354+
get(previous) {
355+
if (count.value <= 3) {
356+
return count.value;
357+
}
358+
359+
return previous;
360+
},
361+
set(newValue) {
362+
count.value = newValue * 2;
363+
}
364+
})
365+
</script>
366+
```
367+
368+
</div>
369+
370+
262371
## ベストプラクティス {#best-practices}
263372

264373
### getter 関数は副作用のないものでなければならない {#getters-should-be-side-effect-free}

0 commit comments

Comments
 (0)