Javascript is required
ยท
1 min read

Vue Tip: Watch Slot Changes

Vue Tip: Watch Slot Changes Image

Sometimes, you need to react to changes in the slot content. For example, if you have a dynamic list of items in a slot, you might want to update the list when the slot content changes.

Unfortunately, Vue does not provide a built-in way to watch slot changes, but you can use the MutationObserver API to react to changes in the slot content. It's a built-in browser API and, thus framework agnostic:

Component.vue
1<script setup lang="ts">
2import { ref, onMounted, onBeforeUnmount } from 'vue';
3
4const slotElement = ref(null);
5const observer = ref(null);
6
7const update = () => {
8  console.log('UPDATE');
9};
10
11onMounted(() => {
12  observer.value = new MutationObserver(update);
13
14  observer.value.observe(slotElement.value, {
15    childList: true,
16    subtree: true,
17  });
18});
19
20onBeforeUnmount(() => {
21  if (observer.value) {
22    observer.value.disconnect();
23  }
24});
25</script>
26
27<template>
28  <div ref="slotElement">
29    <slot />
30  </div>
31</template>

If the component is mounted, we create a new MutationObserver instance and call the observe method to start observing the slot element. We pass the update method as the callback function and an object with the childList and subtree options to observe changes in the slot content.

When the component is unmounted, we call the disconnect method to stop observing the slot element. This is necessary to avoid memory leaks.

StackBlitz

Try it yourself in the following StackBlitz project. Each time you click the "Increment" button, the update method is called and logs a message to the console:

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.