Skip to content
Advertisement

In Vue3 composition API make the watcher work immediately

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')
        }

          });

Advertisement

Answer

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}
   );

Advertisement