Skip to content

Commit

Permalink
feat(guide/computed): add previous to computed (#3001)
Browse files Browse the repository at this point in the history
* feat(guide/computed): add previous to computed

Signed-off-by: GitHub <[email protected]>

* 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 <[email protected]>
Co-authored-by: Natalia Tepluhina <[email protected]>
  • Loading branch information
ferferga and NataliaTepluhina authored Sep 27, 2024
1 parent b1a6899 commit 4567e55
Showing 1 changed file with 109 additions and 0 deletions.
109 changes: 109 additions & 0 deletions src/guide/essentials/computed.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,115 @@ Now when you run `fullName.value = 'John Doe'`, the setter will be invoked and `

</div>

## 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:

<div class="options-api">

```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;
}
}
}
```
</div>

<div class="composition-api">

```vue
<script setup>
import { ref, computed } from 'vue'
const count = ref(2)
// 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
const alwaysSmall = computed((previous) => {
if (count.value <= 3) {
return count.value;
}
return previous;
})
</script>
```
</div>

In case you're using a writable computed:

<div class="options-api">

```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;
}
}
}
}
```

</div>
<div class="composition-api">

```vue
<script setup>
import { ref, computed } from 'vue'
const count = ref(2)
const alwaysSmall = computed({
get(previous) {
if (count.value <= 3) {
return count.value;
}
return previous;
},
set(newValue) {
count.value = newValue * 2;
}
})
</script>
```

</div>


## Best Practices {#best-practices}

### Getters should be side-effect free {#getters-should-be-side-effect-free}
Expand Down

0 comments on commit 4567e55

Please sign in to comment.