vue 作用域插槽学习笔记

作用域插槽

动态的给插槽绑定数据,和给组件传值的prop属性类似,只不过换了个名称而已。

  1. Vue 2.6.0 之后2.x版本中slotslot-scope属性任被支持,但不会出现在vue3中了。
    slot 指定要匹配插槽的名称
  <div id="main">
    <el-list :list="list">
      <template slot="web" slot-scope="slotScope"> <!-- 具体的可以通过结构简化 -->
        {
   
   { slotScope }}
      </template>
    </el-list>
  </div>
  <script src="./vue.js"></script>
  <script>
    Vue.component("ElList", {
     
     
      template: '<ul> \
        <li v-for="item in list" :key="item.id"> \
          <slot name="web" v-bind="item" v-bind:row="row"></slot> \
        </li> \
      </ul>',
      props: {
     
     
        list: {
     
     
          type: Array,
          default: function() {
     
     
            return []
          }
        }
      },
      data: function() {
     
     
        return {
     
     
          row: {
     
      title: 'web' }
        }
      }
    })
    new Vue({
     
     
      el: '#main',
      data: function() {
     
     
        return {
     
     
          list: [
            {
     
     
              id: 1,
              name: 'html',
              age: 18
            }
          ]
        }
      }
    })
  </script>
  1. Vue 2.6.0之后,新的语法v-slot 简写 #,默认插槽的名称是default
  <div id="main">
    <el-list :list="list">
      <template #web="slotScope"> <!-- 具体的可以通过结构简化 -->
        {
   
   { slotScope }}
      </template>
    </el-list>
  </div>
  <script src="./vue.global.js"></script>
  <script>
    Vue.createApp({
      data: function() {
        return {
          list: [
            {
              id: 1,
              name: 'html',
              age: 18
            }
          ]
        }
      }
    }).component("ElList", {
      template: '<ul> \
        <li v-for="item in list" :key="item.id"> \
          <slot name="web" v-bind="item" v-bind:row="row"></slot> \
        </li> \
      </ul>',
      props: {
        list: {
          type: Array,
          default: function() {
            return []
          }
        }
      },
      data: function() {
        return {
          row: { title: 'web' }
        }
      }
    }).mount('#main')

输出结果

都是相同的结果
输出结果

猜你喜欢

转载自blog.csdn.net/u013270347/article/details/110352680