E
E
Egor Danchenko2022-01-30 18:04:37
Vue.js
Egor Danchenko, 2022-01-30 18:04:37

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)

But here's the bad luck, the computed "posts" property is called when store.state.search.query (the string containing the query) changes. And such a question, how does he know about this dependency, if it is specified only in the body of the property. The most interesting thing is that if this line (store.state.search.query) is not in the body, then the computed property is not called (checked through the console). Also here is the link to the repository . Unleash the magic please :)
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

1 answer(s)
D
Dmitry Belyaev, 2022-01-30
@YahorDanchanka

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 question

Ask a Question

731 491 924 answers to any question