Answer the question
In order to leave comments, you need to log in
How does Vue JS find computed dependencies?
I have a calculated property "posts" that returns posts, depending on the search string. Previously, I thought that computed only finds dependencies based on the return statement. For example (i.e. this.firstName and this.lastName dependencies):
const fullName = computed(() => this.firstName + ' ' + this.lastName)
const posts = computed(() => {
const query: string = store.state.search.query
if (query) {
return store.state.posts.filter((post: IPost) => {
return query
.toLowerCase()
.split(' ')
.every((v) => post.title.toLowerCase().includes(v))
})
}
return store.state.posts
})
Answer the question
In order to leave comments, you need to log in
All reactive object properties Vue wraps in getters and setters.
Computed is also essentially a getter, although Vue also wraps it with its own code.
Before each start of computed, Vue puts a function in a special variable to invalidate the current computed, and before exiting, it restores the value that was there before.
Each getter called inside computed simply stores the invalidation function in the array, and pulls it in the setter, thereby telling the computed property that its dependency has changed.
This is a very simplified scheme, since in reality everything is a little more complicated. But in general terms, Vue just knows which getters were called the last time computed was called, and when the setters corresponding to those getters are called, it recalculates computed.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question