slot插槽
插槽简介
插槽就是⼦组件中的提供给⽗组件使⽤的⼀个占位符,⽤slot 表示,⽗组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换⼦组件的slot标签,当⼀个组件有不确定的结构时, 就需要使⽤slot 技术
注意: 插槽内容是在⽗组件中编译后, 再传递给⼦组件的
作⽤: 让⽗组件可以向⼦组件指定位置插⼊html结构,也是⼀种组件间通信的⽅式,适⽤于 ⽗组件 ===> ⼦组件 。
分类: 默认插槽、具名插槽、作⽤域插槽
插槽的使⽤
- 在⼦组件中放⼀个占位符
<template>
<div>
<h1>今天天⽓状况:</h1>
<slot></slot>
</div>
</template>
<script>
export default {name: 'ChildModel'}
</script>
- 在⽗组件中给这个占位符填充内容
<template>
<div>
<div>使⽤slot分发内容</div>
<div style="margin-top: 30px">
<child-model>
<div>多云,最⾼⽓温34度,最低⽓温28度,微⻛</div>
</child-model>
</div>
</div>
</template>
<script>
import ChildModel from '@/components/ChildModel.vue'
export default {
name: 'FatherModel',
components: {
ChildModel
}
}
</script>
插槽的使⽤ - 具名插槽
- ⼦组件的代码,设置了两个插槽(header和footer)
<div class="header">
<h1>我是⻚头标题</h1>
<div>
<!--这⾥存放⻚头的具体内容-->
<slot name="header"></slot>
</div>
<div class="footer">
<h1>我是⻚尾标题</h1>
<div>
<!--这⾥存放⻚尾的具体内容-->
<slot name="footer"></slot>
</div>
</div>
</div>
</template>
<script>
export default {name: 'ChildModel'}
</script>
- ⽗组件填充内容, ⽗组件通过 v-slot:[name] 或 #[name]的⽅式指定到对应的插槽中
<template>
<div>
<div>使⽤slot分发内容</div>
<div style="margin-top: 30px">
<child-model>
<template v-slot:header>
<h1>我是⻚头的具体内容</h1>
</template>
<template #footer>
<h1>我是⻚尾的具体内容</h1>
</template>
</child-model>
</div>
</div>
</template>
<script>
import ChildModel from '@/components/ChildModel.vue'
export default {
name: 'FatherModel',
components: {
ChildModel
}
}
</script>