【问题标题】:Vue Named Slots Caveat?Vue 命名插槽注意事项?
【发布时间】:2020-05-27 02:48:33
【问题描述】:

当使用带有 Vue 的命名插槽时(使用旧的、更详细的组件插槽 API),如果我有一个使用这样的模板定义的可重用组件:

<template>
 <div v-for="field in formFields">
  <slot name="`${field.key}_PREPEND`">
   <span hidden></span>
  </slot>
  <slot name="`${field.key}_FIELD`">
    <slot name="`${field.key}_LABEL`">{{ field.label }}</slot>
    <slot name="`${field.key}_CONTROL`">
      <input v-if="field.type === 'text'" v-model="model[field.key]"></input>
      <input type="checkbox" v-else-if="field.type === 'checkbox'" v-model="model[field.key]"></input>
    </slot>
  </slot>
  <slot name="`${field.key}_APPEND`">
   <span hidden></span>
  </slot>
 </div>
</template>

(这本质上是我拥有的自动表单生成组件的镂空版本)

然后我可以像这样重用这个组件:

<auto-form
   :fields="someArray"
   :model="someObject"
>
   <template slot="Name_PREPEND"> This goes before the name field </template>
   <template slot="Name_FIELD"> For some reason this isn't being rendered, the default slot markup is</template>
   <template slot="Name_APPEND"> This goes after the name field </template>
</auto-form>

由于某种原因,使用上述标记 (&lt;auto-form&gt;),插槽“${field.key}_FIELD”被忽略。

如果我像这样更改 _PREPEND 字段的内部标记

<slot name="`${field.key}_PREPEND`">
   <span hidden>
     <slot name="`${field.key}_CONTENT`"></slot>
   </span>
 </slot>

我同样不能覆盖 _PREPEND 槽(但可以覆盖 _CONTENT)

这仅仅是 Vue 组件槽的限制吗?即是否不允许嵌套组件槽?

在这种特殊情况下,限制将阻止使用此 AutoForm 组件的开发人员说,通过 _FIELD 插槽同时覆盖控件和标签(对于我的使用,我想添加使特定字段基于表单中其他字段的值)

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    万一其他人遇到这个问题,那就有点偷偷摸摸了。

    看起来如果您对应该覆盖插槽的标记进行条件渲染,则默认插槽将在没有条件渲染时呈现在其位置。

    因此,简单的解决方案是在尝试覆盖组件槽时使用v-show 而不是v-if

    (与最初怀疑的嵌套组件槽无关)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-20
      • 2017-09-08
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 2017-11-06
      • 1970-01-01
      • 2021-02-06
      相关资源
      最近更新 更多