vue父組件插槽內(nèi)容直接訪問子組件的數(shù)據(jù)

1.slot 如何讓插槽內(nèi)容能夠訪問子組件中才有的數(shù)據(jù)

在下面父組件中是沒發(fā)拿到item的值的

// 父組件 father.vue
<todo-list>
  <i class="fas fa-check"></i>
  // 這里是拿不到item的,只有在todo-list組件內(nèi)部才能拿到item
  <span class="green">{{ item }}</span>
</todo-list>

// 子組件 todo-list.vue
items = ['Feed a cat', 'Buy milk']
 <ul>
   <li v-for="(item, index) in items">
     {{ item }}
   </li>
 </ul>

可以通過slot解決 父組件獲取到子組件里的值

// 子組件 todo-list.vue
items = ['Feed a cat', 'Buy milk']
 <ul>
   <li v-for="(item, index) in items">
   // 這里可以根據(jù)自己的需要將任意數(shù)量的 attribute 綁定到 slot 上
    <slot :item='item' :index='index'></slot>
   </li>
 </ul>

綁定在 <slot> 元素上的 attribute 被稱為插槽 prop。現(xiàn)在,在父級(jí)作用域中,我們可以使用帶值的 v-slot 來定義我們提供的插槽 prop 的名字:

// 父組件
<todo-list>
// slotProps這個(gè)名字可以任意
 <template #default="slotProps">
   <i class="fas fa-check"></i>
   <span class="green">{{ slotProps.item }}</span>
 </template>
</todo-list>

// 等價(jià)于
<todo-list #default="slotProps">
  <i class="fas fa-check"></i>
  <span class="green">{{ slotProps.item }}</span>
</todo-list>
 
// 也等價(jià)于
<todo-list v-slot="slotProps">
  <i class="fas fa-check"></i>
  <span class="green">{{ slotProps.item }}</span>
</todo-list>

// 也可以這樣 {item} 結(jié)構(gòu)賦值
<todo-list v-slot="{ item,index }">
  <i class="fas fa-check"></i>
  <span class="green">{{ item }}</span>
</todo-list>
最后編輯于
?著作權(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)容