Vue高級(jí)特性「六」--slot 插槽

基本使用

父組件在引用的子組件中添加內(nèi)容

<slotDemo :url="website.url">
  {{website.title}} //父組件添加的內(nèi)容
</slotDemo>
data() {
  return {
    website:{
      url:'http://www.baidu.com',
      title:'百度',
    },
  };
},

子組件 slotDemo.vue

<template>
  <div>
    <a :href="url">
      <slot>
        默認(rèn)內(nèi)容,即父組沒設(shè)置內(nèi)容是,這是顯示
      </slot>
    </a>
  </div>
</template>

作用域插槽

父組件可以拿到子組件的數(shù)據(jù)

  • 1.把組件的的數(shù)據(jù)website 綁定到 slot 的一個(gè)自定義屬性slotDate上
  • 2.在父組件里定義 template 設(shè)置v-slot為任意命名參數(shù)slotProps,
  • 3.數(shù)據(jù)取值為:slotProps.子組件命名數(shù)據(jù).具體數(shù)據(jù)字段

子組件 ScopedSlotDemo.vue

<template>
  <div>
    <a :href="url">
    //把組件的的數(shù)據(jù)website 綁定到 slot 的一個(gè)自定義屬性slotDate上
      <slot :slotDate="website"> 
        {{website.title}} 
      </slot>
    </a>
  </div>
</template>

<script>
export default {
  props: ['url'],
  data() {
    return {
      website:{
        url:'http://www.baidu.com',
        title:'百度1',
        subTitle:'百度一下,你就知道1'
      }
    };
  },
};
</script>

父組件 調(diào)用數(shù)據(jù)

<ScopedSlotDemo :url="website.url">
  //在 template 設(shè)置v-slot為任意命名參數(shù)slotProps,
  // 取值 slotProps.子組件slot上自定義屬性slotDate.子組件數(shù)據(jù)
  <template v-slot="slotProps">
    {{slotProps.slotDate.title}}
  </template>
</ScopedSlotDemo>

具名插槽

子組件 NameSlot 定義多個(gè)solt添加 name屬性來標(biāo)識(shí)

<div>
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <solt></solt>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

父組件:通過v-slot:name 來匹配到相同name的子組件

<NameSlot>
  <template v-slot:header>
    <h1>將插入 header slot中</h1>
  </template>
  <p>將插入 main slot中,及未命名的slot</p>
  <template v-slot:footer>
    <h1>將插入 footer slot中</h1>
  </template>
</NameSlot>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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