Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(guide/computed): add previous to computed #3001

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions src/guide/essentials/computed.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,114 @@ 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;
})
```
</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