Vue slot的使用
一、什么是slot
- 在子组件中,使用特殊的元素就可以为子组件开启一个插槽
- 该插槽插入什么内容取决于父组件如何使用
二、插槽的基本使用
在子组件中使用为子组件开启一个插槽
<template>
<div class="hello">
这是子组件内部!
<slot></slot>
</div>
</template>
在父组件中使用该组件,并为slot填充内容
<template>
<div id="app">
<HelloWorld>
<div>
这是填充的内容
</div>
</HelloWorld>
</div>
</template>
效果图:
这就是slot的基本用法:
- 在子组件中固定位置
- 在父组件中填充内容
三、具名插槽
具名插槽:具名插槽就是具有名字的插槽(应该是这样理解的吧)
具名插槽的使用:非常的简单只要给slot一个name属性,它便升级为了具名插槽。
在子组件中添加一个带有name属性的slot
<template>
<div class="hello">
这是子组件内部!
<slot name="top"></slot>
</div>
</template>
在父组件中插入的内容添加一个slot属性
<template>
<div class="hello">
这是子组件内部!
<slot name="top"></slot>
</div>
</template>
这便是具名插槽的使用。
效果图:
到这就有人想问了,这具名插槽就只用这点用处吗?
当然不是了!
当子组件的功能复杂的时候,一个插槽往往是不能解决问题的。这就需要多个插槽。但普通的插槽怎么去区分哪个插槽呢?这就有了具名插槽
子组件中分别有具名slot top和bottom 还有一个普通插槽
<template>
<div class="hello">
这是子组件内部!
<slot name="top"></slot>
<slot></slot>
<slot name="bottom"></slot>
</div>
</template>
在父组件中当然也是需要那么多的东西传进去了
<template>
<div id="app">
<HelloWorld>
<div slot="top">
这是具名top插槽填充的内容
</div>
<div>
这是普通插槽填充的内容
</div>
<div slot="bottom">
这是具名bottom插槽填充的内容
</div>
</HelloWorld>
</div>
</template>
效果图:
四、终极使用(作用域插槽)
作用域插槽是插槽中比较难以理解的一个点。
这里,我们用一句话来对其做一个总结,然后再后面的案例中体会。
- 父组件替换插槽的标签,但是内容由子组件提供
需求:
- p子组件中包括一组数据,比如:pLanguages: [‘JavaScript’, ‘Python’, ‘Swift’, ‘Go’, ‘C++’]
- 需要再多个界面中展示
内容在子组件,希望父组件告诉我们如何展示。
怎么办???
利用作用域插槽就可以了。
在子组件中通过 **:data=“list”**传值
子组件代码:
<template>
<div class="hello">
<slot :data="list"></slot>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data(){
return {
list: ['JavaScript', 'Python', 'Swift', 'Go', 'C++']
}
}
}
</script>
通过获取到slotProps属性,在通过slotProps.data就可以获取到刚才我们传入的data了
父组件代码:
<template>
<div id="app">
<HelloWorld>
<template slot-scope="slotScope">
<ul v-for="item in slotScope.data" :key="item">
<li>{{item}}</li>
</ul>
</template>
</HelloWorld>
</div>
</template>
效果图:
五、补充使用:
父组件代码:
<template>
<about :aaa="aaa">
<template #left="left">
letf-index:{{left.index}}
</template>
<template #center="center">
center-index:{{center.index}}
</template>
<template #right="right">
right-index:{{right.index}}
</template>
</about>
</template>
<script>
import about from './componets/about.vue'
export default {
name: 'App',
components:{
about
},
data(){
return {
aaa:'bbb'
}
}
}
</script>
<style>
</style>
子组件代码:
<template>
<h2>about:{{aaa}}</h2>
<div>
<template v-for="item of item">
<slot :name="item.name" :index="item.index"></slot>
</template>
</div>
</template>
<script>
export default {
name:'AppAbout',
props:{
aaa:{
type:String
}
},
data(){
return {
item:[{name:'left',index:1},{
name:"center",index:2
},{
name:"right",index:3
}]
}
}
}
</script>
<style>
</style>
效果图: