【问题标题】:How to make parent data accessible to nested slots' props (Vue 2)?如何使嵌套插槽的道具(Vue 2)可以访问父数据?
【发布时间】:2021-12-18 08:07:50
【问题描述】:

在高层次上,假设我有:

<parent>
    <template v-slot:content="{foo, bar}"> // foo/bar are just data from parent that contains "FOO" / "BAR"
         <child :v-text="foo" :someprop="bar === 'BAR'"> // foo and bar are accessible here
              <template v-slot:content>
                  <grandchild :v-text="foo" :someprop="bar === 'BAR'"> // foo and bar are no longer accessible here
                  </grandchild>
              </template>
         </child>
    </template>
</parent>

通过这种方式,我可以从父级范围传递任意数据,并且直接子级可以访问该数据。但是,如果孩子也有插槽,则该孩子的孩子将失去祖父母插槽的上下文(除非我手动从孩子公开其插槽模板中来自父母的数据,我猜)。这些嵌套插槽甚至可以深入到曾孙。

有没有一种解决方案可以让曾孙子女的道具值可以使用父数据?

【问题讨论】:

    标签: javascript vue.js vuejs2 vuejs-slots


    【解决方案1】:

    您可以在中间组件内的父插槽模板内创建一个命名插槽。

    此示例将项目属性传回给子项

    父组件

    <slot name='content' :item='item'>
      Replace Me
    </slot>
    
    

    中间组件

    <parent>
      <template #content='{item}'>
        <slot name='content' :item='item' />
      </template>
    </parent>
    

    子组件

    <middle>
      <template #content='{item}'>
        the item is {{item}}
      </template>
    </middle>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-08
      • 2020-01-30
      • 2022-07-06
      • 2022-01-08
      • 2022-11-29
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      相关资源
      最近更新 更多