在composition-api中watch hook的使用?



我在Options API中有以下代码:

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

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

watch选项的等效Composition API为watch()。假设$things是一个全局属性,使用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 }
)
}
}

最新更新