• vue 中的插槽 slot


    一、作用:

    让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件 。

    二、分类:

    默认插槽、具名插槽、作用域插槽

    三、使用方式:

    1、默认插槽:

    子组件中(插槽组件):

        <template>
           <div>
             <!-- 定义插槽 -->
             <slot>插槽默认内容...</slot>
           </div>
        </template>
    

    父组件中(使用插槽的组件):

        <Category>
           <div>html结构1</div>
        </Category>
    

    2、具名插槽:

    子组件中(插槽组件):

        <template>
           <div>
            <!-- 定义插槽 -->
              <slot name="center">插槽默认内容...</slot>
              <slot name="footer">插槽默认内容...</slot>
           </div>
        </template>
    

    父组件中(使用插槽的组件):

        <Category>
           <template slot="center">
                <div>html结构1</div>
           </template>
          
         //vue2.6.0后的新语法:具名插槽使用 v-slot,取代了 slot 和 slot-scope
           <template v-slot:footer>
                <div>html结构2</div>
           </template>
        </Category>
    

    3、作用域插槽:

    理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)
    具体编码:
    子组件中(插槽组件):

      <template>
        <div>
          <slot :games="games"></slot>
        </div>
      </template>
             		
     <script>
        export default {
          name:'Category',
          props:['title'],
          //数据在子组件自身
          data() {
             return {
                games:['红色警戒','穿越火线','劲舞团','超级玛丽']
                    }
                  },
         }
     </script>
    

    父组件中(使用插槽的组件):

     <Category>
        <template scope="scopeData">
            <!-- 生成的是ul列表 -->
             <ul>
              <li v-for="g in scopeData.games" :key="g">{{g}}</li>
             </ul>
         </template>
     </Category>
             
      <Category>
         <template slot-scope="scopeData">
            <!-- 生成的是h4标题 -->
            <h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
         </template>
      </Category>
    
    <Category>
         <template v-slot="scopeData">
            <!-- 生成的是p标签 -->
            <p v-for="g in scopeData.games" :key="g">{{g}}</p>
         </template>
      </Category>
    

    template有三种写法,scopeslot-scopev-slot,最新写法是v-slot,vue3中只能使用v-slot
    以上 scopeData是插槽组件中传过来的数据,是一个对象,比如插槽组件中是这样

    <template>
        <div>
          <slot :games="games" :msg="msg"></slot>
        </div>
      </template>
    

    那么scopeData接收到的数据就是

    {games:...,msg:...}
    

    scopeData也可以使用es6中的解构赋值,比如这个scopeData对象中有两个或者多个数据,我们只用到games,那么我们可以直接使用v-slot="{games}"解构赋值

      <Category>
         <template v-slot="{games}">
            <h4 v-for="g in games" :key="g">{{g}}</h4>
         </template>
      </Category>
    
  • 相关阅读:
    asp.net web生命周期
    图的数据结构1
    最长公共子串
    内部排序

    棋盘覆盖问题
    队列
    矩阵连乘问题
    图的数据结构2
    旅行售货员问题
  • 原文地址:https://www.cnblogs.com/qingheshiguang/p/15062128.html
Copyright © 2020-2023  润新知