vue---slot插槽

一、什么是插槽?

在進(jìn)行組件化開發(fā)時(shí),通常會遇到同一個(gè)功能,有共性的部分,也有不同的部分,此時(shí)我們就需要在子組件內(nèi),將不同的部分預(yù)留一個(gè)槽口即<slot></slot>,此時(shí)父組件在調(diào)用子組件時(shí),就可以通過預(yù)留的槽口向子組件內(nèi)插入不同的內(nèi)容,實(shí)現(xiàn)不同內(nèi)容的動態(tài)化展示,子組件內(nèi)預(yù)留的槽口<slot></slot> 就是插槽。

二、插槽的作用

多個(gè)模塊間具有相同的部分,又有各自不同的功能時(shí),此時(shí)如果不想多次寫重復(fù)的代碼時(shí),就可以將該多個(gè)模塊抽取為一個(gè)公共組件,不同的部分設(shè)置插槽,父組件調(diào)用時(shí)通過插槽動態(tài)傳遞內(nèi)容即可。下面是插槽應(yīng)該的小例子,一個(gè)模塊的標(biāo)題是一樣的,但是展示內(nèi)容不一致。

三、插槽的應(yīng)用

子組件

<template>
  <div>
    <p>listData</p>
    <slot>
      <ul>
        <li v-for="item in listData" :key="item.name">{{item.name}}</li>
      </ul>
    </slot>
  </div>
</template>

父組件

<template>
  <div>
    <Cslot>
      <h4>自己插入的插槽</h4>
    </Cslot>

    <Cslot></Cslot>
  </div>
</template>

四、具名插槽

有時(shí)我們需要多個(gè)插槽時(shí),需要給子組件內(nèi)的插槽定義一個(gè)名字,確保父組件在插入時(shí),可以一 一對應(yīng)。一個(gè)不帶 name 的 <slot> 出口會帶有隱含的名字“default”。

子組件

<template>
  <div>
    <p>listData</p>
    <slot>
      <ul>
        <li v-for="item in listData" :key="item.name">{{item.name}}</li>
      </ul>
    </slot>
    
    <slot name="centerSlot">
      <p>我是中間的slot</p>
    </slot>
  </div>
</template>

父組件 通過v-slot組件綁定需要對應(yīng)的slot名稱即可 即:v-slot:centerSlot 也可以簡寫為#centerSlot(適用于template模板)

<template>
  <div>
    <Cslot></Cslot>
    <Cslot>
     <template #centerSlot> 
      <div>具名插槽</div>
      <h4>自己插入的插槽</h4>
    </template>

    </Cslot>
  </div>
</template>

也可以不通過template 直接在元素上綁定需要插入的插槽名字,當(dāng)與template同時(shí)存在時(shí),template優(yōu)先級最高

<template>
  <div>
    <Cslot></Cslot>
    <Cslot>
     <div slot='centerSlot'> 
          <div>具名插槽</div>
          <h4>自己插入的插槽</h4>
      </div>
    </Cslot>
  </div>
</template>

五、作用域插槽,(為了讓插槽內(nèi)容能夠訪問子組件中的數(shù)據(jù))即父組件需要獲取子組件的數(shù)據(jù) 重新修改渲染。

父組件有自己的作用域,只能訪問自己作用域內(nèi)的數(shù)據(jù)。

具體實(shí)現(xiàn),子組件在slot上通過綁定屬性將數(shù)據(jù)綁定上
父組件需要通過template模板 通過v-slot指令 獲取對應(yīng)slot傳過來的數(shù)據(jù)(是一個(gè)對象:{{centerData:listData}},需要點(diǎn)傳遞時(shí)的屬性[centerData]獲取具體傳過來的值[listData])。代碼如下

子組件

<template>
  <div>
    <slot name="centerSlot" v-bind:centerData="listData">
      <p>我是中間的slot</p>
    </slot>
  </div>
</template>

父組件

<template>
  <div>
    <current-slot></current-slot>
    <current-slot>
      <template v-slot:centerSlot="slotProps">
        <span v-for="item in  slotProps.centerData" :key="item.name">---{{item.age}}---</span>
      </template>
    </current-slot>
  </div>
</template>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容