Slot
slot主要作用是内容分发,即在父组件内的子组件标签里边定义子组件的内容,此部分内容中的简单插槽,具名插槽,作用域插槽必须要掌握
- 最简单的插槽
父组件
<template>
<div>
<Child>
<ul>
<li v-for="user in data" :key="user">{{user}}</li>
</ul>
</Child>
</div>
</template>
<script>
import Child from './Child'
export default{
name:'Parent',
component:{Child},
data(){
return{
data:['kiki','pp','lili']
}
}
}
</script>
子组件
<template>
<div>
<p>人员名单:</p>
<--父组件中引用的子组件的li名单渲染将在子组件中添加-->
<slot></slot>
</div>
</template>
- 具名插槽
具名插槽即在子组件中定义slot,并使用name属性给插槽取名,在父组件使用时,使用子组件中的插槽名(在父组件使用插槽时,如果使用v-slot=""插入,则只能在template上使用v-slot)
父组件:
<template>
<div>
<Child>
<ul slot='title>
<li v-for="user in data" :key="user">{{user}}</li>
</ul>
</Child>
</div>
</template>
<script>
import Child from './child'
export default{
name:'Parent',
components:{Child},
data(){
return {
data:['lili','pop','cici']
}
}
}
</script>
子组件
<template>
<div>
<slot name='title'></slot>
<slot name='footer'><p> this is footer</p></slot>
</div>
</template>
- 作用域插槽(传数据的插槽)
父组件
<template>
<div>
<Child>
<template v-slot='title' slot-scope="{someWords}">
<ul slot-scope='{users}'>
<li v-for='user in users' :key='users'>{{user}}</li>
</ul>
</template>
</Child>
</div>
</template>
子组件
<template>
<div>
<slot name='title :someWords='someWords'></slot>
<slot :users='users'></slot>
</div>
</template>
<script>
export default{
name:'Child',
data(){
return {
users:['lili','pop','kiki'],
someWords:'这是'
}
}
}
</script>
- 透传插槽
将内层组件的(作用域)插槽通过一层一层的传递出来,以便在外层组件可以将内容传进内层组件的(作用域)插槽中,每一层组件均可以向下一层组件的(作用域)插槽中传递内容,最终均会被传递到最深一级组件的(作用域)插槽中。(该用法一般用在封装复用性组件或者高阶组件上,请不要将所有UI组件的插槽都传递到顶层组件,避免造成滥用)
顶级组件
<template>
<div id="top"> <!-- id只是用来标记组件,开发中去掉即可 -->
<MiddleComponent>
<template slot="MiddleComponent" slot-scope="{data}">
<div>
在 TopComponent 中显示 BottomComponent 组件的作用域插槽传出来的数据:{{data}}
</div>
<div style="margin-top:20px;color: #00acd6;">
这是 TopComponent 传到 MiddleComponent 组件的插槽的内容,它最终会显示在 BottomComponent 组件的插槽中
</div>
</template>
</MiddleComponent>
</div>
</template>
<script>
import MiddleComponent from './MiddleComponent'
export default {
name: 'TopComponent',
components: { MiddleComponent },
}
</script>
中间组件
<template>
<div id="middle"> <!-- id只是用来标记组件,开发中去掉即可 -->
<BottomComponent>
<template slot="BottomComponent" slot-scope="{data}">
<slot name="MiddleComponent" :data="data"></slot>
<div style="margin-top:20px;color: #e08e0b">
这是 MiddleComponent 传递给 BottomComponent 组件的插槽的内容
</div>
</template>
</BottomComponent>
</div>
</template>
<script>
import BottomComponent from './BottomComponent'
export default {
name: 'MiddleComponent',
components: { BottomComponent }
}
</script>
底层组件
<template>
<div id="bottom"> <!-- id只是用来标记组件,开发中去掉即可 -->
<slot name="BottomComponent" :data="str">这是 BottomComponent 插槽的后备内容</slot>
</div>
</template>
<script>
export default {
name: 'BottomComponent',
data () {
return {
str: 'BottomComponent'
}
}
}
</script>