Blog>
Snippets

Slot content and VDOM updates in Vue 3

Show how to pass content to child components using slots and how changes in content affect VDOM patching.
<template>
  <button @click="updateMessage">Change Message</button>
  <child-component>
    <template #default="slotProps">
      <p>{{ slotProps.message }}</p>
    </template>
  </child-component>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const message = ref('Hello, Vue 3!');

    function updateMessage() {
      message.value = 'Updated message!';
    }

    return { message, updateMessage };
  }
};
</script>
Vue 3 component template that includes a child component with a default slot. The child component displays a message passed to it through the slot's scoped slotProps. A button is provided to update this message, showcasing how changes to the slot content are handled in Vue's Virtual DOM.
<script>
import { h } from 'vue';

export default {
  render() {
    return h('div', this.$slots.default({
      message: this.message
    }));
  },
  props: {
    message: String
  }
};
</script>
Child component script using the render function to receive content passed via slots. It renders a div with the content of the default slot and provides a 'message' prop that is accessible to the slot content.
<style>
p {
  color: green;
}
</style>
CSS styling for the paragraph element that will show inside the slot, where the message will be rendered.