How to Watch Deep Data Structures in Vue (Arrays and ... | vue watch deep data
Youhaveanarrayoranobjectasaprop,andyouwantyourapptodosomethingwheneverthatdatachanges.Soyoucreateawatcherforthatproperty,butVuedoesntseemtofirethewatcherwhenthenesteddatachanges.Hereshowyousolvethis.YouneedtosetdeeptotruewhenwatchinganarrayorobjectsothatVueknowsthatitshouldwatchthenesteddataforchanges.Illgointomoredetailonwhatthislookslikeinthisarticle,plussomeotherusefulthingstoknowwhenusingwatchinVue.WhatwellcoverinthisarticleFirstwelldoaquickrefresheronwhatawatcheractuallyis.Thenwelldivei...
You have an array or an object as a prop, and you want your app to do something whenever that data changes.
So you create a watcher for that property, but Vue doesnt seem to fire the watcher when the nested data changes.
Heres how you solve this.
You need to set deep to true when watching an array or object so that Vue knows that it should watch the nested data for changes.
Ill go into more detail on what this looks like in this article, plus some other useful things to know when using watch in Vue.
What well cover in this articleFirst well do a quick refresher on what a watcher actually is.
Then well dive into how you can watch nested data in arrays and objects.
What is a watcher?In Vue we can watch for when a property changes[1], and then do something in response to that change.
For example, if the prop colour changes, we can decide to log something to the console:
import { watch } from vue;
const props = defineProps({