Complete the code to create a cleanup function inside onMounted in Vue Composition API.
<script setup> import { onMounted, [1] } from 'vue' onMounted(() => { const cleanup = () => { console.log('Cleanup done') } [1](() => { cleanup() }) }) </script>
watch instead of a lifecycle hook.onMounted without unmount hook.In Vue, onUnmounted is used to run cleanup code when the component is removed.
Complete the code to register an event listener and clean it up properly in Vue Composition API.
<script setup> import { onMounted, [1] } from 'vue' onMounted(() => { const onResize = () => { console.log('Window resized') } window.addEventListener('resize', onResize) [1](() => { window.removeEventListener('resize', onResize) }) }) </script>
watch instead of lifecycle hooks.onUnmounted is used to remove event listeners when the component is destroyed to avoid memory leaks.
Fix the error in the cleanup function scope to properly remove the event listener.
<script setup> import { onMounted, onUnmounted } from 'vue' let onScroll onMounted(() => { onScroll = () => { console.log('Scrolled') } window.addEventListener('scroll', [1]) }) onUnmounted(() => { window.removeEventListener('scroll', onScroll) }) </script>
addEventListener and trying to remove a different function.onMounted.The event listener must be removed with the exact same function reference used when adding it. Using onScroll ensures this.
Fill both blanks to create a reactive ref and clean it up properly.
<script setup> import { ref, [1], [2] } from 'vue' const count = ref(0) [1](() => { const interval = setInterval(() => { count.value++ }, 1000) return () => clearInterval(interval) }) </script>
onMounted without cleanup.watchEffect.watchEffect runs the effect and returns a cleanup function. onUnmounted is imported but not used here.
Fill all three blanks to properly setup and cleanup a custom event listener with Vue Composition API.
<script setup> import { onMounted, [1], ref } from 'vue' const message = ref('') onMounted(() => { const onCustomEvent = (event) => { message.value = event.detail } window.addEventListener('custom-event', onCustomEvent) [2](() => { window.removeEventListener('custom-event', [3]) }) }) </script>
removeEventListener.onUnmounted is used to clean up the event listener. The same function onCustomEvent must be passed to removeEventListener.