Watchers | Nuxt watch
BasicExample[1]Computedpropertiesallowustodeclarativelycomputederivedvalues.However,therearecaseswhereweneedtoperform"sideeffects"inreactiontostatechanges-forexample,mutatingtheDOM,orchanginganotherpieceofstatebasedontheresultofanasyncoperation.WiththeOptionsAPI,wecanusethewatchoption[2]totriggerafunctionwheneverareactivepropertychanges:jsexportdefault{data(){return{question:,answer:Questionsusuallycontainaquestionmark.;-),loading:false}},watch:{//wheneverquestionchanges,thisfunctionwillrun...
Basic Example [1]Computed properties allow us to declaratively compute derived values. However, there are cases where we need to perform "side effects" in reaction to state changes - for example, mutating the DOM, or changing another piece of state based on the result of an async operation.
With the Options API, we can use the watch option[2] to trigger a function whenever a reactive property changes:
jsexport default { data() { return { question: , answer: Questions usually contain a question mark. ;-), loading: false } }, watch: { // whenever question changes, this function will run question(newQuestion, oldQuestion) { if (newQuestion.includes(?)) { this.getAnswer() } } }, methods: { async getAnswer() { this.loading = true this.answer = Thinking... try { const res = await fetch(https://yesno.wtf/api) this.answer = (await res.json()).answer } catch (error) { ...