Using Vue3 composition API. How do I make watched to work immediately. The following code doesn't work.
watch((immediate=true) => props.isOpen, () => {
if (props.isOpen && props.preventBackgroundScrolling) {
document.body.style.setProperty('overflow', 'hidden')
} else {
document.body.style.removeProperty('overflow')
}
});
To watch props change with Vue Composition API and Vue 3, we can use the watch function. to call watch to watch the selected prop. We get the latest and previous value of it from the parameters in the 3rd argument.
The Vue. js Watcher or watch property allows the developers to listen to the component data and run whenever they change a particular property. The watcher or watch property is a unique Vue. js feature that lets you keep an eye on one property of the component state and run a function when that property value changes.
Vue 3 introduced Composition API which allows developers to write components in a better way. Using this API, developers can group the logical pieces of code together, which in turn helps write readable code. Composition API is a built in feature in Vue 3 and is also available in Vue 2 via @vue/composition-api plugin.
The watch API is part of the larger Vue Composition APIs. Learn how to track data changes in Vue 3 applications and much more. The watch API is part of the larger Vue Composition APIs.
Vue 3 comes with the Composition API built-in. It lets us extract logic easily an not have to worry about the value of this in our code. It also works better with TypeScript because the value of this no longer has to be typed. In this article, we’ll look at how to create Vue 3 apps with the Composition API.
Before Composition API was introduced, Vue 2 was using Options API. While developers can still use Options API in Vue 3, the problem with it is that one single topic would be fragmented across different options such as data () or props, certain methods, some lifecycle hooks ( mounted (), created (), and more), and watchers ( watch ).
The watch function in the Vue 3 composition API is the same as Vue 2’s this.$watch method or the watch option. Therefore, we can use it to watch for changes in reactive properties.
It should placed as option :
watch(() => props.isOpen, () => {
if (props.isOpen && props.preventBackgroundScrolling) {
document.body.style.setProperty('overflow', 'hidden')
} else {
document.body.style.removeProperty('overflow')
}
},{immediate:true});
or
watch('props.isOpen', () => {
if (props.isOpen && props.preventBackgroundScrolling) {
document.body.style.setProperty('overflow', 'hidden')
} else {
document.body.style.removeProperty('overflow')
}
},
{immediate:true}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With