美文网首页
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中作用域插槽

    目的:插槽内容能够访问子组件中才有的数据是很有用的 直接上代码 父组件 子组件

  • Vue高级特性「六」--slot 插槽

    基本使用 父组件在引用的子组件中添加内容 子组件 slotDemo.vue 作用域插槽 父组件可以拿到子组件的数据...

  • 作用域插槽

    ***父级在其子组件插槽想要访问子组件插槽数据时候,可以通过子组件的slot插槽暴露出去的props去访问。 使用...

  • 【Vue】组件 - 插槽默认值

    基础知识 【Vue】组件 - 插槽的基本用法 【Vue】组件 - 多个插槽 子组件里,在 里写上默认的内容。 在父...

  • vue中的slot——作用域插槽

    作用域插槽的作用是可以访问子组件的数据,相当于父组件可以直接在slot范围内使用子组件的数据。如果对插槽的基本知识...

  • 插槽v-slot

    父子组件插槽的使用 父组件product.vue 子组件 ProductParam.vue

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

    1.slot 如何让插槽内容能够访问子组件中才有的数据 在下面父组件中是没发拿到item的值的 可以通过slot解...

  • vue父子组件的访问方式

    有时候我们需要父组件直接访问子组件,子组件直接访问父组件,或者是子组件访问跟组件。 父组件访问子组件:使用$chi...

  • Vue学习(5)-插槽slot

    插槽就是子组件预留给父组件放置内容的空间,如果没有插槽,那么我们在父组件中使用子组件时,往子组件里添加内容是无效的...

  • vue具名插槽使用

    插槽用法:子组件header固定;父组件outside插槽header/index.vue outside/ind...

网友评论

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

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