【Vue插槽】 slot用法,使用场景
匿名插槽,具名插槽,作用域插槽插槽,slot用法,使用场景
·
1.什么是插槽
Vue 实现了一套内容分发的 API,将 <slot> 元素作为承载分发内容的出口。
作用是:在父组件中向子组件中传递定制化的内容
插槽有3种分类 (只是用法有细微差别,原理一毛一样)
1.匿名插槽:没有名字的插槽
2.具名插槽:有名字(name属性)的插槽
3.作用域插槽:子组件中的数据只能子组件访问到,但是我们的插槽往往定义在父组件中,这个时候就需要作用域插槽来打通他们之间的关系,然后就能在父组件中愉快的使用子组件的数据了
2.什么时候使用插槽
当子组件被复用时,需要在特定的区域展示不同的定制化的内容。
3.使用
3.1.匿名插槽(默认插槽)
<!--父组件内容-->
<template>
<div>
<!--子组件标签-->
<Category>
<!--子组件标签体内容,也就是需要插入的内容-->
<a href="#" slot="footer">更多信息</a>
</Category>
</div>
</template>
<!--子组件内容-->
<template>
<div>
<h3>{{title}}分类</h3>
<!-- 在<slot>标签位置显示插入的内容-->
<slot></slot>
</div>
</template>
3.2.具名插槽
需要使用多个插槽的时候,定义一个name属性,区分插槽对应的位置。
<!--父组件内容-->
<template>
<div>
<Category title="美食" :listData="foods" >
<img slot="center" src=""/>
<a slot="footer" href="#">更多信息</a>
</Category>
</div>
</template>
<!--子组件内容-->
<template>
<div class="category">
<h3>{{title}}分类</h3>
<slot name="center"> slot标签,这个位置也可以写内容 </slot>
<slot name="footer"></slot>
</div>
</template>
<!-- slot="center" 对应 name="center" -->
<!-- slot="footer" 对应 name="footer" -->
3.3.作用域插槽
当父组件需要用到子组件里的数据时,通过插槽传递数据。
<!--父组件内容-->
<template>
<div class="container">
<Category title="游戏">
<!--需要包裹一个template标签(必须),获取slot传递数据-->
<template scope="{ info }">
<ul>
<li v-for="(item, index) in info.games" :key="index">{{ item }}</li>
</ul>
</template>
</Category>
</div>
</template>
<!--子组件内容-->
<template>
<div class="category">
<h3>{{ title }}分类</h3>
<!--通过slot传递数据info-->
<slot :info="info">test </slot>
</div>
</template>
更多推荐
已为社区贡献10条内容
所有评论(0)