Vue implements a content distribution API inspired by the Web Components spec draft, using the <slot> element to serve as distribution outlets for content.
- Slot Content — Content written within parent template. This content will get rendered in the allotted placeholder of the child template
- Compilation Scope — Everything in the parent template is compiled in parent scope; everything in the child template is compiled in the child scope.
- Fallback Content — Content provided by the child template. If parent template does not provide explicit content, then whatever is written within child template will be rendered.
- Named Slots — There could be multiple slots within client template. To uniquely identify them, we need to provide value to the name attribute.
- Scoped Slots — A mechanism to access data in the child scope from the parent template via slot props
- Dynamic Slot Names
Understanding all these concepts are slightly difficult for beginners, if we read and use them based on the guide or known syntax. We have to learn using a real problem to solve.
Assume, we need to create a shared component called v-data-table. Typically, table component has to provide the following features
- Accept headers as props
- Accept items (table content) as props
- Provide a well-formed table with necessary styles as best defaults
- Allow users (developers) to customize specific columns based on their specific needs
Point# 4 is “tricky” to implement. With v-slot, this will be a breeze.
In the below table, developer wants to customize the text color of Message column based on its value.
Line 20–22 details about Named Slot, Dynamic Slot Names and Fallback Content— Create one slot per header name (table column). If user does not want to customize the column, he will not provide the slot in his client code.
Line 6–8 allows you to customize one of the column “msg”. Rest of the columns will be rendered based on the fallback content.