• 默认插槽
    没有给插槽定义name属性的插槽为默认插槽
  • 具名插槽
    带name值的插槽为,具名插槽
  • 案例演示
    • APP.vue
      <template>
          <SlotTest>
              <!-- 具名插槽 -->
              <h3 slot="name1">{{title}}</h3>
              <!-- 默认插槽 -->
              <slot>1111</slot>
          </SlotTest>
      </template>
      <script>
      import SlotTest from './components/SlotTest.vue'
      export default {
          name: "App",
          data(){
              return{
                  title:"标题"
              }
          },
          components:{
              SlotTest
          }
      };
      </script>
      <style scoped>
      </style>
      
    • SlotTest.vue
      <template>
          <div>
              <slot name="name1">SlotTest组件标题</slot>
              <slot name="name2">SlotTest组件标题</slot>
              <slot>222</slot>
          </div>
      </template>
      <script>
      export default {
          name: "SlotTest",
      };
      </script>
      <style scoped>
      </style>
      
  • 插槽作用域
    • App.vue
      <template>
              <!-- 作用域插槽 -->
          <SlotTest :todos="todos">
              <!-- 
                  scope:是一个对象,对象上有todo,index顺序
                  v-slot指定slot回传过来的所有属性和数据
                    v-slot 是新语法
                    slot-scope 是老语法
               -->
              <template v-slot="scope">
                  <span>父组件上回传的~~{{scope.todo}}~~{{scope.index}}</span>
              </template>
          </SlotTest>
      </template>
      <script>
      import SlotTest from './components/SlotTest.vue'
      export default {
          name: "App",
          data(){
              return{
                  todos:[
                      {id:1,name:"张三1",bool:true},
                      {id:2,name:"张三2",bool:false},
                      {id:3,name:"张三3",bool:false}
                  ]
              }
          },
          components:{
              SlotTest
          }
      };
      </script>
      <style scoped>
      </style>
      
    • SlotTest.vue
      <template>
          <ul>
              <li v-for="(todo,index) in todos" :key="todo.id">
                  <span :style="{color:todo.bool?'red':'blue'}">子组件上~~{{todo.id}}~{{todo.name}}~~{{todo.bool}}</span>
                  <!-- slot标签上的所有属性都会自动传递给父组件 -->
                  <slot :todo="todo" :index="index"></slot>
              </li>
          </ul>
      </template>
      <script>
      export default {
          name: "SlotTest",
          props:{
              todos:Array
          }
      };
      </script>
      <style scoped>
      </style>
      
posted on 2021-07-13 23:32  文种玉  阅读(389)  评论(0编辑  收藏  举报