Sometimes you want the supplied component to have a reusable slot that gets the data from the subassembly. For example, a template for a simple <todo-list>
component might contain the following code:
<ul> <Li V-for="Todo in Todos" v-bind:key="Todo.id" > {{Todo.text}} </li> </ul>
|
But in some parts of our application, we want each individual backlog to render todo.text
something that is not quite the same. This is also where the scope slot comes in.
To make this feature possible, all you need to do is wrap the backlog <slot>
on an element, and then pass all of its context-sensitive data to the slot: in this case, the data is the todo
object:
<Ul> <Li V-for="Todo in Todos" v-bind:key= "Todo.id" <!--we have a slot for each TODO, --> <!--to pass the ' Todo ' object as a slot prop. --> <slot v-bind:todo= "Todo", <!--fallback content--> </SLOT> Span class= "line" > </li>, < /UL> |
Now when we use <todo-list>
the component, we can choose to define a different alternative for the to-do item <template>
, and we can get the slot-scope
data from the subcomponents through the attributes:
<Todo-listv-bind:todos="Todos" > <!--define ' Slotprops ' as the name of the socket scope--> <template slot-scope= Span class= "line" > <!--customize a template for Todo items,--> <span v-if= "SlotProps.todo.isComplete";? </SPAN> {{SlotProps.todo.text}} </template>, </< Span class= "name" >TODO-LIST> |
In 2.5.0+, it is slot-scope
no longer restricted to <template>
use on elements, but can be used on any element or component in a slot.
Deconstruction
slot-scope
If a JavaScript expression is valid in a function-defined parameter position, the expression can actually be slot-scope
accepted. This means you can use the ES2015 deconstruction syntax in these expressions in a supported environment (single-file component or modern browser). For example:
<v-bind:todos="Todos" > <slot-scope="{todo}" > <v-if="Todo.iscomplete";? </span> {{Todo.text}} </template> </todo-list>
|
This makes the scope slots cleaner.
Scope usage of slot slots (excerpt from Vue.js official website)