vue父组件插槽内容直接访问子组件的数据

2022-02-10  本文已影响0人  lemonzoey

1.slot 如何让插槽内容能够访问子组件中才有的数据

在下面父组件中是没发拿到item的值的

// 父组件 father.vue
<todo-list>
  <i class="fas fa-check"></i>
  // 这里是拿不到item的,只有在todo-list组件内部才能拿到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">
   // 这里可以根据自己的需要将任意数量的 attribute 绑定到 slot 上
    <slot :item='item' :index='index'></slot>
   </li>
 </ul>

绑定在 <slot> 元素上的 attribute 被称为插槽 prop。现在,在父级作用域中,我们可以使用带值的 v-slot 来定义我们提供的插槽 prop 的名字:

// 父组件
<todo-list>
// slotProps这个名字可以任意
 <template #default="slotProps">
   <i class="fas fa-check"></i>
   <span class="green">{{ slotProps.item }}</span>
 </template>
</todo-list>

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

// 也可以这样 {item} 结构赋值
<todo-list v-slot="{ item,index }">
  <i class="fas fa-check"></i>
  <span class="green">{{ item }}</span>
</todo-list>
上一篇下一篇

猜你喜欢

热点阅读