我认为最好用一个使用纯 JavaScript 函数的示例来说明。
把组件想象成一个函数,例如
function todoList(todos) {
// render <ul>, loop todos, render <li> and todo.text
}
现在假设该函数能够传递一个名为 slot 的可选内容渲染函数
function todoList(todos, slot) {
slot = slot || slotProps => {
// render slotProps.todo.text
}
// render <ul>
todos.forEach(todo => {
// render <li>
slot({ todo }) // call "slot" function
}
}
分配给slot的函数相当于
<slot v-bind:todo="todo">
<!-- Fallback content -->
{{ todo.text }}
</slot>
来自示例。
所以现在当你调用这个函数时,你可以选择使用类似的东西
todoList(todos, slotProps => {
if (slotProps.todo.isCompleted) {
// render a checkmark, eg ✓
}
// render slotProps.todo.text
})
这里传入的函数相当于
<template slot-scope="slotProps">
<!-- Define a custom template for todo items, using -->
<!-- `slotProps` to customize each todo. -->
<span v-if="slotProps.todo.isComplete">✓</span>
{{ slotProps.todo.text }}
</template>
在示例中。