Skip to content

05作用域插槽

2.1.0 新增

作用域插槽是一种特殊类型的插槽,用作使用一个(能够传递数据到)可重用模板替换已渲染元素。 在子组件中,只需将数据传递到插槽,就像你将 prop 传递给组件一样:

<div class="child"> <slot text="hello from child"></slot> </div>

在父级中,具有特殊属性 scope 的 <template> 元素,表示它是作用域插槽的模板。scope 的值对应一个临时变量名,此变量接收从子组件中传递的 prop 对象:

<div class="parent"> <child> <template scope="props"> <span>hello from parent</span> <span>{{ props.text }}</span> </template> </child> </div>

<div class="parent"> <div class="child"> <span>hello from parent</span> <span>hello from child</span> </div> </div>

作用域插槽更具代表性的用例是列表组件,允许组件自定义应该如何渲染列表每一项:

<my-awesome-list :items="items"> <!-- 作用域插槽也可以在这里命名 --> <template slot="item" scope="props"> <li class="my-fancy-item">{{ props.text }}</li> </template> </my-awesome-list>

列表组件的模板:

<ul> <slot name="item" v-for="item in items" :text="item.text"> <!-- fallback content here --> </slot> </ul>

共 20 个模块,1301 篇 Markdown 文档。