'What does slot mean in vue's render function
In vue, there is a slot option in render function, the document says "slot is the name of the slot, if this component is the child of another component". I can not understand what it means. My understanding is that the slot name is the node returned by createElement function's name as a slot, but it seems wrong. My English is poor, I am sorry if I didn't describe the question clearly.
Vue.component('render-component', {
render(h) {
return h('div', {
class: 'main'
}, [
h('div', { slot: 'header' }, 'header'),
h('div', { slot: 'footer' }, 'footer')
])
}
})
let vm = new Vue({
el: '#app',
data() {
return {
message: 123
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<render-component>
<template v-slot:header>111111</template>
</render-component>
</div>
Solution 1:[1]
Option slot
means that result of render function will be inserted into slot of component that was used in first param.
Vue.component('card-component', {
template: `
<div>
<h1>Hello</h1>
<strong><slot/></strong>
<i><slot name="note" /></i>
</div>
`
});
Vue.component('parent-component', {
render(h) {
const defaultSlotContent = h('p', {}, 'default description');
const namedSlotContent = h('p', {slot: 'note'}, 'It is a note')
return h('card-component', {}, [defaultSlotContent, namedSlotContent]);
}
});
let vm = new Vue({
el: '#app',
data() {
return {
message: 123
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<parent-component />
</div>
Solution 2:[2]
Take a look at Vue’s introduction to slots to understand what a slot is. The example you are looking at is a shorthand using a render function to render an array of named slots. It is roughly equivalent to this code from the docs:
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
A named slot allows you to specify multiple slots within a component (without a name it merely defaults). Everything within the relevant <template>
element for the slot will then be passed to the slots, e.g.:
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kostenko Maxim |
Solution 2 | radbyx |