基本使用/具名插槽/作用域插槽
基本使用/具名插槽:
在标签中嵌套slot,定义name="slotname",export default 到处组件。在父组件中引用此组件,并在组件中写上template 标签,标签内写上#slotname。这是简写。
//引用插槽的父组件
// 父组件代码
<template>
<div id="app">
<slotDemoVue :type="'large'">
<template #body>
请输入<input />
</template>
</slotDemoVue>
</div>
</template>
<script>
import slotDemoVue from './components/slot-demo.vue'
export default {
name: 'App',
components: {
slotDemoVue
}
</script>
<style>
</style>
——————————————————————————————————————————————————————————————————————————————————————
//插槽对应代码
<template>
<div class="slotDemo" :class="type=='default'?'default':type">
<div class="header">头部</div>
<div class="body">
<slot name="body">
</slot>
</div>
<div class="footer">脚</div>
</div>
</template>
<script>
export default {
name: 'slotDemo',
props: {
type:{
type:String,
default() {
return 'default'
}
}
}
}
</script>
<style>
.default {
width: 100px;
height: 200px;
background: red;
}
.large {
width: 200px;
height: 400px;
background: yellow;
}
</style>
作用域插槽:
在slot标签内写上 :slotData="变量名" ,在父组件中引用插槽时在<template>标签内写上 v-slot:body="fromChildData" 。通过 {{fromChildData['slotData']}} 引用子组件插槽中的数据。
示例代码
// 父组件
<template>
<div id="app">
<slotDemoVue :type="'large'">
<template v-slot:body="fromChildData">
{{fromChildData}}
</template>
</slotDemoVue>
</div>
</template>
<script>
import slotDemoVue from './components/slot-demo.vue'
export default {
name: 'App',
components: {
slotDemoVue
}
}
</script>
<style>
</style>
————————————————————————————————————————————————————————————————————————————
//子组件
<template>
<div class="slotDemo" :class="type=='default'?'default':type">
<div class="header">头部</div>
<div class="body">
<slot name="body" :slotData1="roleList">
插槽默认内容1
</slot>
<slot name="body1" :slotData="roleList1">
插槽默认内容2
</slot>
</div>
<div class="footer">脚</div>
</div>
</template>
<script>
export default {
name: 'slotDemo',
props: {
type:{
type:String,
default() {
return 'default'
}
}
},
data() {
return {
roleList: [
{
name:'jack',
habit:'Pop'
},
{
name:'mark',
habit:'say'
}
],
roleList1: [
{
name:'jack',
habit:'Pop'
},
{
name:'mark',
habit:'say'
}
]
}
}
}
</script>
<style>
.default {
width: 100px;
height: 200px;
background: red;
}
.large {
width: 200px;
height: 400px;
background: yellow;
}
</style>