Vue Slot

Reference List

  1. https://cn.vuejs.org/v2/guide/components-slots.html

Slot的作用

語法小提示:由slot的標籤就是子組件,有v-slot v指令的是父組件。

父組件和子組件的含義

以我現在的理解,組件A包含組件B,A就是B的父組件。

Slot含義

slot的含義是相對於子組件而言。子組件是父組件的組成部分。子組件定義的時候,某個位置不知道填什麼標籤,可能是一個圖片,可能是一段文字。這個時候就把它抽象的描述爲一塊插槽。類似抽象類。

小實驗:

這是我的項目結構:
在這裏插入圖片描述
TestSlot是父組件,它使用子組件ChildSlot。

  • ChildSlot.vue
<template>
  <button type="submit">
    <!--這裏定義一個插槽,可以是一個img,可以是一個文字-->
    <slot>Submit</slot>
  </button>
</template>
<script>
  export default{
    name:"ChildSlot"
  }
</script>
<style>
</style>

父組件在使用它的時候,就可以往這個插槽裏放任意標籤:

  • TestSlot.vue
<template>
    <!--這是一個代碼約定,ChildSlot(駝峯式)要在html中變成child-slot-->
    <child-slot>Yet Another Commit</child-slot>
</template>

<script>
   //將子組件引用進來
   import ChildSlot from './ChildSlot'
   export default{
     name:"TestSlot",
     //在組件列表中包含子組件
     components:{
         ChildSlot
     }
 }
</script>

<style>
</style>

可以看到最終渲染的html

在這裏插入圖片描述
如果換成:

  • TestSlot.vue
<template>
    <child-slot><img src="../assets/logo.png"/></child-slot>
</template>

Dom會被渲染成:
在這裏插入圖片描述

插槽作用域(父組件訪問子組件data屬性)

子組件:

<template>
  <span>
    <!--設定插槽prop,這種屬性對父組件可見-->
    <slot v-bind:user="user">{{ user.lastName }}</slot>
  </span>
</template>

<script>
  export default{
    name:"ChildSlot",
    data(){
      return{
        user:{
          firstName:"oneslide",
          lastName:"icywater"
        }
      }
    }
  }
</script>

父組件使用user屬性:

<template>
    <child-slot>
       <!--這裏的default代表默認具名插槽的名字-->
       <template v-slot:default="cprops">
          {{cprops.user.firstName}}
       </template>
    </child-slot>
</template>

回想具名插槽的使用語法,其實後面就是加一個="cprops"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章