vue中插槽的使用非常广泛,本文就插槽的使用和理解简单总结。
从字面理解插槽是预先插入一个代码空间,用于后期塞入数据。
插槽分类
匿名插槽 ------------------ 匿名的代码空间
具名插槽 ------------------ 带有命名的代码空间
作用域插槽 ------------------- 带有数据的代码空间
插槽使用示例
匿名插槽
说明在组件中先定义预留的代码空间,组件在使用时直接写入代码
<template>
<div class="child">
<h3>这里是子组件</h3>
<slot></slot>
</div>
</template>
使用:
<template>
<div class="father">
<h3>这里是父组件</h3>
<child>
<div class="tmpl">
<span>菜单1</span>
<span>菜单2</span>
<span>菜单3</span>
<span>菜单4</span>
<span>菜单5</span>
<span>菜单6</span>
</div>
</child>
</div>
</template>
具名插槽
预先在组件中定义一个带有名称的代码空间,使用组件时用:slot绑定名称
<template>
<div class="child">
// 具名插槽
<slot name="up"></slot>
<h3>这里是子组件</h3>
// 具名插槽
<slot name="down"></slot>
// 匿名插槽
<slot></slot>
</div>
</template>
使用:
<template>
<div class="father">
<h3>这里是父组件</h3>
<child>
//插槽up
<div class="tmpl" slot="up">
<span>菜单1</span>
<span>菜单2</span>
<span>菜单3</span>
<span>菜单4</span>
<span>菜单5</span>
<span>菜单6</span>
</div>
//插槽down
<div class="tmpl" slot="down">
<span>菜单-1</span>
<span>菜单-2</span>
<span>菜单-3</span>
<span>菜单-4</span>
<span>菜单-5</span>
<span>菜单-6</span>
</div>
//匿名插槽
<div class="tmpl">
<span>菜单->1</span>
<span>菜单->2</span>
<span>菜单->3</span>
<span>菜单->4</span>
<span>菜单->5</span>
<span>菜单->6</span>
</div>
</child>
</div>
</template>
作用域插槽 (有数据,但放开了渲染)
在组件中预先定义一个带有数据资源的代码空间,使用组件时可以直接使用代码空间中的数据
定义
<template>
<div class="child">
<h3>这里是子组件</h3>
// 作用域插槽
<slot :data="data"></slot>
</div>
</template>
export default {
data: function(){
return {
data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba']
}
}
}
使用
<template>
<div class="father">
<h3>这里是父组件</h3>
<!--第一次使用:用flex展示数据-->
<child>
<template slot-scope="user">
<div class="tmpl">
<span v-for="item in user.data">{{item}}</span>
</div>
</template>
</child>
<!--第二次使用:用列表展示数据-->
<child>
<template slot-scope="user">
<ul>
<li v-for="item in user.data">{{item}}</li>
</ul>
</template>
</child>
<!--第三次使用:直接显示数据-->
<child>
<template slot-scope="user">
{{user.data}}
</template>
</child>
<!--第四次使用:不使用其提供的数据, 作用域插槽退变成匿名插槽-->
<child>
我就是模板
</child>
</div>
</template>
总结:
匿名插槽和具名插槽的功能是 预留插入代码的空间;
作用域插槽是提供数据资源,预留代码渲染逻辑空间。