YanLipu
YanLipu

Reputation: 3

Using of watch hook in composition-api?

I have the following code in Options API:

  ...
  watch: {
    $things: {
      async handler(val, oldVal) {
        this.someFunction()
        if(this.someVariable) this.getSomethingHere()
      },
      deep: true
    }
  },
  ...
})

How to refactor this code to composition-api using watch hook?

Upvotes: 0

Views: 567

Answers (1)

tony19
tony19

Reputation: 138306

The equivalent Composition API for the watch option is watch(). Assuming $things is a global property, use getCurrentInstance().appContext.config.globalProperties to access $things:

import { watch, getCurrentInstance } from 'vue'

export default {
  setup() {
    const someFunction = () => {/*...*/}
    const getSomethingHere = () => {/*...*/}
    let someVariable = true

    const globals = getCurrentInstance().appContext.config.globalProperties
    watch(
      () => globals.$things,
      async handler(val, oldVal) {
        someFunction()
        if (someVariable) getSomethingHere()
      },
      { deep: true }
    )
  }
}

Upvotes: 1

Related Questions