我在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 }
)
}
}