composition-api中watch hook的使用?

Using of watch hook in composition-api?

我在选项 API 中有以下代码:

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

如何使用 watch hook 将这段代码重构为 composition-api?

watch 选项的等效组合 API 是 watch(). Assuming $things is a global property,使用 getCurrentInstance().appContext.config.globalProperties 访问 $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 }
    )
  }
}