slot作为插槽,一般用在封装组件中,通过被调用时可以自定义填充内容
1. 初级使用
<div>
<div>我是父级页面</div>
<swage> //子组件
我是往插槽中填充的内容
</swage>
</div>
<div>
<div>swage Vue--插槽上端</div>
<slot></slot>
<div>swage Vue--插槽下端</div>
</div>
此时页面显示为:
我是父级页面
swage Vue--插槽上端
我是往插槽中填充的内容
swage Vue--插槽下端
这是最初级的使用方法
2. 当然,一个组件可以被安装多个插槽,只需要给不同的名字。
默认一个插槽时其实也有个默认名字叫default,当使用多个插槽时如下
<div>
<div>我是父级页面</div>
<swage>
<template v-slot:title>
我是标题
</template>
我将在default中展示
<template v-slot:bottom>
我是底部
</template>
</swage>
</div>
<div>
<div>swage Vue--插槽上端</div>
<slot name="title"></slot>
<div> <slot></slot></div>
<div>swage Vue--插槽下端{{ text }}</div>
<slot name="bottom"></slot>
</div>
此时页面显示为:
我是父级页面
swage Vue--插槽上端
我是标题
我将在default中展示
我是往插槽中填充的内容
swage Vue--插槽下端
我是底部
这是多个不同插槽的用法
3. 关于插槽中使用变量我这边引用一句官方的原话
**父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。**
如果你想在父组件中,访问子组件插槽中的变量你需要通过如下定义一个接收的值:
<div>
<div>我是父级页面</div>
<swage>
<template v-slot:title="nameList">
{{ nameList.userinfo.firstName }}
</template>
</swage>
</div>
<div>
<div>swage Vue--插槽上端</div>
<slot name="title" :userinfo="userinfo"></slot>
</div>
data(){
return{
text:'TEXT VALUE',
userinfo:{
firstName:'000',
lastNname:'999'
}
}
}
此时父组件的nameList就接受到了子组件中的userinfo
页面就会被渲染成
我是父级页面
swage Vue--插槽上端
000
4. 最后按照官方文档做了一个小demo
<div>
<div>我是父级页面</div>
<swage v-slot:todo="item">
<span v-if=" item.childItem.id>5">{{ item.childItem.id }}</span>
</swage>
</div>
<div>
<div v-for="(item,index) in arr" :key="index">
<slot name="todo" :childItem="item"></slot>
</div>
</div>
data(){
return{
arr:[
{id:3},
{id:4},
{id:5},
{id:6},
{id:7}
]
}
}
子组件在循环时每次都会创建一个slot,父组件获取子组件中的每一项,大于5的则会展示
重点在于父组件中取值是应该取子组件slot中绑定的键,上文中是childItem,
所以父组件中使用就应该是==》父组件先定义的作用域变量item==》子组件中定义的每一项键childItem===》原数据格式id==最终为==》item.childItem.id