vue插槽slot的简单理解与用法实例分析

2020-06-16 06:39:26易采站长站整理

</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>

总结:

匿名插槽和具名插槽的功能是 预留插入代码的空间

作用域插槽是提供数据资源,预留代码渲染逻辑空间

希望本文所述对大家vue.js程序设计有所帮助。