Ryan Durham
Senior Engineer @ Phylos
Owner @ Stage Right Labs
ryan at stagerightlabs dot com
Scoped Slots + Renderless Components =
Game Changer
Slots allow parent components to inject
content into child components.
|
|
Child Heading
Hello World!
What if you want to inject into multiple locations?
You can have as many named slots as you want,
in addition to the default slot.
|
|
Parent Heading
Hello World!
What if you want to refer to child component data?
"Scoped" slots have access to child component data.
|
|
// App.vue - Parent
<template #header="{ user }">
{{ user.name }}
</template>
Hello World!
// App.vue
<template #header="{ user }">
{{ user.name }}
</template>
<template #default="{ prop }">
{{ prop.example }}
</template>
The slot API we are looking at is from Vue 2.6+. If you are using an earlier version of Vue things will work exactly the same, but the API is slightly different.
// MyComponent.vue
Hello {{ name }}
createElement()
generates virtual nodes that will be inserted into Vue's virtual DOM.
createElement()
// @returns {VNode}
createElement(
'div', // String or function that returns a tag name
// {String | Array}
// Children VNodes, built using `createElement()`,
// or using strings to get 'text VNodes'. Optional.
[
'Some text comes first.',
createElement('h1', 'A headline'),
createElement(MyComponent, {
props: {
someProp: 'foobar'
}
})
]
)
https://vuejs.org/v2/guide/render-function.html
createElement()
is sometimes called h()
Use the Template Explorer to see how render functions are generated by Vue behind the scenes:
What happens when we combine render
functions and scoped slots?
// MyComponent.vue
This is now a "renderless" component.
// App.vue
<template #default="{ user }">
{{ user.name }}
</template>
"Renderless" components allow us to inject functionality that does not rely on specific UI/UX.
Shift + Click Range Selection
https://codesandbox.io/s/xoy96vw0oMore about slots:
by Adam Wathan
ryan at stagerightlabs dot com