作用:让父组件可以向子组件指定的位置插入html结构,也是一种组件间通信的方式,适用于父组件===>子组件
分类:默认插槽、具名插槽、作用域插槽
父组件:
- <Category>
- <div>html结构1div>
- Category>
例:
- <Category title="美食">
- <h1>我是美食h1>
- Category>
子组件:
- <tempalte>
- <div>
-
- <solt>插槽的默认内容<solt>
- div>
- tempalte>
例:
- <template>
- <div class="category">
- <slot name="food">我是一个插槽slot>
- div>
- template>
具名插槽,就是给插槽加入name属性
父组件:
- <Category>
- <tempalte slot='center'>
- <div>html结构1div>
- tempalte>
- <Category>
例:
- <template>
- <div class="container">
- <Category>
- <h1 slot="food">我是美食h1>
- Category>
- div>
-
- template>
子组件:
- <tempalte>
- <div>
-
- <slot name='center'>插槽的默认内容...slot>
- tempalte>
例:
- <template>
- <div class="category">
- <h1>{{title}}h1>
- <slot name="food">我是一个food插槽slot>
- div>
- template>
作用域插槽,与前两者的不同 slot自定义:name="值" 子组件可向父组件传递信息
理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者决定。(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)
具体编码---父组件:
- <Category>
- <tempalte slot-scope='scoperData'>
-
- <ul>
- <li v-for='g in scoperData.games' :key='g'>li>
- ul>
- tempalte>
- Category>
-
- <Category>
- <tempalte slot-scope='scoperData'>
-
- <h4 v-for='g in scoperData.games' :key='g'>h4>
- tempalte>
- Category>
具体编码---子组件:
- <tempalte>
- <div>
- <slot :games='games'>slot>
- div>
- <tempalte>
-
- <script>
- export default{
- name:'Category',
- props:['title'],
-
- data:{
- return{
- games:['穿越火线','超级玛丽','王者荣耀']
- }
- }
- }
- script>