美文网首页
vue父组件插槽内容直接访问子组件的数据

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

作者: lemonzoey | 来源:发表于2022-02-10 17:11 被阅读0次

    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>
    

    相关文章

      网友评论

          本文标题:vue父组件插槽内容直接访问子组件的数据

          本文链接:https://www.haomeiwen.com/subject/rnankrtx.html