Vue JS Vue JS Slots and Scoped Slots 1 — Questions and Answers
Question 1: What is the primary purpose of a slot in Vue JS?
- A placeholder in a child component's template where parent-provided content is rendered (Correct answer)
- A reactive data property declared inside a component
- A lifecycle hook that runs after the component is mounted
- A special Vuex module for sharing state
Correct answer: A placeholder in a child component's template where parent-provided content is rendered
Slots are placeholders in child component templates that allow parent components to inject and render custom content in designated areas.
Question 2: Which built-in Vue element defines a slot inside a child component's template?
- <slot> (Correct answer)
- <template>
- <outlet>
- <content>
Correct answer: <slot>
The `<slot>` element is Vue's reserved element used in child templates to mark where parent-injected content should be rendered.
Question 3: What renders when a parent component does NOT provide content for a slot?
- The fallback content placed between the slot's opening and closing tags (Correct answer)
- An empty string with no visible output
- The component throws a runtime error
- A default Vue.js placeholder icon
Correct answer: The fallback content placed between the slot's opening and closing tags
Any content written between `<slot>` and `</slot>` acts as fallback content and is displayed only when the parent provides nothing for that slot.
Question 4: How do you define a named slot called 'header' in a child component?
- <slot name="header"> (Correct answer)
- <slot id="header">
- <template slot="header">
- <named-slot>header</named-slot>
Correct answer: <slot name="header">
Named slots are declared in the child using the `name` attribute on the `<slot>` element, e.g., `<slot name="header">`.
Question 5: How does a parent component target a named slot called 'footer'?
- <template v-slot:footer> (Correct answer)
- <template slot-name="footer">
- <div slot="footer">
- <slot target="footer">
Correct answer: <template v-slot:footer>
The `v-slot:slotName` directive is placed on a `<template>` element in the parent to route content into the matching named slot of the child.
Question 6: What is the shorthand syntax for the `v-slot:header` directive?
- #header (Correct answer)
- @header
- :header
- ~header
Correct answer: #header
The `#` symbol is the shorthand for `v-slot:`, making `#header` exactly equivalent to `v-slot:header`.
Question 7: On which elements can the `v-slot` directive be used?
- Only on <template> elements or directly on component tags (Correct answer)
- On any HTML element including divs and spans
- Only on <div> elements inside the component
- Only inside <script setup> blocks
Correct answer: Only on <template> elements or directly on component tags
Vue restricts `v-slot` to `<template>` elements or directly on a component's tag when targeting the default slot in shorthand form.
What is the primary purpose of a slot in Vue JS?