插槽的应用

130 阅读1分钟

Slot 通俗的理解就是 “占坑” ,在组件模板中占好了位置,当使用该组件标签时候,组件标签里面的内容就会自动“填坑”,替换组件模板中slot位置,并且可以作为承载分发内容的出口。

  1. 作用:让父组件可以向子组件指定位置插入 html 结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件 。
  2. 分类:默认插槽、具名插槽、作用域插槽
  3. 使用方式

(1)默认插槽

//Category子组件中:
<template>
  <div>
    <!-- 定义插槽 -->
    <slot>插槽默认内容...</slot>
  </div>
</template>
//父组件中:
<Category>
    <div>html结构1</div>
</Category>

(2)具名插槽
如果slot没有name属性,就是匿名插槽了,而父组件中不指定slot属性的内容,就会被丢到匿名插槽中。

//子组件中:
<template>
  <div>
    <!-- 定义插槽 -->
    <slot name="center">插槽默认内容,这里可以为空...</slot>
    <slot name="footer">插槽默认内容,这里可以为空...</slot>
  </div>
</template>
//父组件中:
<Category>
        //旧版本写法
        <template slot="center">
          <div>html结构1</div>
        </template>
        
        //这个v-slot只能用在template标签上
        //在父组件中`v-slot:footer`可以缩写为`#footer`
        <template v-slot:footer>
           <div>html结构2</div>
        </template>
</Category>
//在父组件上使用`v-slot:插槽名称`,这个是vue2.6.0以后的写法,在vue2.6.0之前,可以在模板上使用slot="插槽的名称"

(3)作用域插槽

  • 理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。(games数据在Category组件中,但使用数据所遍历出来的结构由App组件(父组件)决定)
// 父组件
<Category title="游戏">
    <template scope="atguigu">  //atguigu是对象(插槽传过来的动态数据)
        <ul>
            <li v-for="(g,index) in atguigu.games" :key="index">{{g}}</li>
        </ul>
    </template>
</Category>
<Category title="游戏2">
    <template scope="{games}">
        <ol>
            <li style="color:red" v-for="(g,index) in games" :key="index">{{g}}</li>
        </ol>
    </template>
</Category>
<Category title="游戏3">
    <template slot-scope="{games}">
        <h4 v-for="(g,index) in games" :key="index">{{g}}</h4>
    </template>
</Category>
// 子组件
<template>
    <div class="category">
        <h3>{{title}}分类</h3>
        <slot :games="games" msg="hello">我是默认的一些内容</slot>
    </div>
</template>
<script>
    export default {
        name:'Category',
        props:['title'],
        data() {
            return {
                games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
            }
        },
    }
</script>