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>
<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>
<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>