In Vue, we can watch for property changes using watchers. If a prop or data changes, we can fire a function based on that change. Let’s look at how it works.
Join the DZone community and get the full member experience. In any web application, it’s normal to have input data that alters a page. For example, a user may update their username, or submit a post. In vue, we can watch for these changes using watchers. Watchers allow us to check on a specific data element or prop and see if it’s been altered in any way. If you are brand new to Vue, get started with our guide on making your first Vue app here, before diving into watchers. When we make new components in Vue, that is, a.vue file we can watch for changes in data or props by using the watch. For example, the below code will watch for a change in the data element pageData, and run a function according to the value it is changed to. Similarly, we can watch for prop changes using the same methodology. The below example watches for a change in a prop called ” name “: If we want to retrieve the old value, i.e. the value that the data or prop was before the change, we can retrieve that using the second argument within a watch function. For example, the below code will now console log both the new value of pageData, and the old value: Now that we have an idea of how watchers work – Let’s look at a real-life example.