Skip to content

Accessing previous value with watcher #539

Answered by posva
3zzy asked this question in Help and Questions
Discussion options

You must be logged in to vote

You need to clone the object if you want to watch an object and still get the previous state (https://v3.vuejs.org/guide/reactivity-computed-watchers.html#watching-reactive-objects)

import _ from 'lodash';

watch(
  () => _.cloneDeep(ScopeStore.$state),
  (state, prevState) => {
    // ....
  }
);

Another solution is to watch the specific attribute(s) you want:

watch(() => ScopeStore.$state.categoryId, (id, prevId) => {
  // ...
})
// watching multiple sources
watch(() => [ScopeStore.$state.categoryId, ScopeStore.$state.other, ([id, other], [prevId, prevOther]) => {
  // ...
})

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by 3zzy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants