Vue-插槽

93 阅读1分钟

插槽

1.插槽的作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间的通行,适用于父组件===>子组件

2.分类:默认插槽、具名插槽、作用域插槽

默认插槽:让父组件可以向子组件指定位置插入html结构,默认插槽写再多也没有用,插入的html结构都会在同一插槽中

语法: <solt><solt>

使用方法:

    父组件中:
        <Category>
            <div>html结构<div>
        </Category>
    子组件:
        <template>
            <div>
                <slot>插槽默认内容</slot>
            </div>
        </template>

具名插槽:可以添加多个插槽,给插槽添加一个名字,根据插槽的名字来决定html插入到那个插槽

语法:<solt name='xxx'></solt>

使用方法:

    父组件中:
        <Category>
            <template slot='xxx'>
                <div>html结构</div>
            </template>
        </Category>
    子组件中:
        <template>
           <div>
                <slot name='xxx'>插槽默认内容</slot>
                <slot name='xxx2'>插槽默认内容</slot>
           <div>
        </template>

作用域插槽:

1.理解:数据再组件的自身,但根据数据生成的结构需要组件的使用者来决定。(games数据再Category组件中,但使用数据所遍历出来的结构由App组件决定)

语法:

<solt :data="data"></solt> 发送数据

<template scope="data"> 收数据

使用方法:

父组件:
​
    <template>
      <div id="app">
    <!--    作用域插槽-->
        <Classification>
        //接收插槽的数据
          <template scope="{games}">
            <ul>
              <li v-for="(i,index) in games" :key="index">{{i}}</li>
            </ul>
          </template>
        </Classification>
​
​
        <Classification>
​
          <template scope="{games}">
            <ol>
              <li v-for="(i,index) in games" :key="index">{{i}}</li>
            </ol>
          </template>
​
        </Classification>
      </div>
    </template>
​
    <script>
    import Classification from "@/components/Classification";
    export default {
      name: "App",
      components:{Classification}
    }
    </script>
​
​
  子组件:
    <template>
      <div class="box">
        <h3>分类</h3>
        //发送数据
        <slot :games="games"></slot>
      </div>
    </template>
​
    <script>
    export default {
      name: "Classification",
      data(){
        return{
          games:['穿越火线','永劫无间','王者荣耀']
        }
      }
    }
    </script>