by ng12 · 6y ago · 0 comments
To take the example from the Vue docs:
// Component with a slot
<ul>
<li v-for="todo in filteredTodos" v-bind:key="todo.id">
<slot name="todo" v-bind:todo="todo">
{{ todo.text }}
</slot>
</li>
</ul>
// Consuming component
<todo-list v-bind:todos="todos">
<template v-slot:todo="{ todo }">
<span v-if="todo.isComplete">x</span>
{{ todo.text }}
</template>
</todo-list>
This can be rewritten in React with much simpler, cleaner code: // Component with a "slot"
<ul>
{filteredTodos.map(todo => props.renderTodo ? props.renderTodo(todo) : todo.text)}
</ul>
// Consuming component
<TodoList todos={todos} renderTodo={todo =>
`${todo.isComplete ? "x " : ""}${todo.text}`
}/>
Simplicity is key. In the React version you don't have to worry about the `slot` syntax, build a mental model of how Vue treats it, or risk running into the limitations of the feature.I just don't like mixing html and js like that, maybe that's why it also seems messy to me.
The vue example also isn't the greatest, some cruft could be removed using default slot and shorter syntax.
> Where's the span for x?
I assumed Vue was only using the span for v-if, in React we don't need that extra node.
> <li>'s are generated by magic?
Whoops -- an omission on my part. They should be wrapping the inside of the mapping function.
> I just don't like mixing html and js like that, maybe that's why it also seems messy to me.
But this is where the magic is. It's exactly why React didn't need to invent a concept for "slots". I admit it's vaguely unfamiliar at first but if it increases both the power and simplicity of your template it's a no-brainer.
On the second note it's copy-pasted code from the official Vue docs.