【问题标题】:Vue.js how to use attributes on slotsVue.js 如何在插槽上使用属性
【发布时间】:2021-05-17 11:33:06
【问题描述】:

是否可以在插槽上设置属性,然后父元素获取这些属性?

父母

<vDropdown>
  <button slot="button">new button</button>
  <ul>content</ul>
</vDropdown>

Dropdown.vue

<div>
  <slot name="button" aria-haspopup="true">
    //fallback
    <button aria-haspopup="true">Default Button</button>
  </slot>
  <div id="name" :aria-expanded="expanded">
    <slot />
  </div>
</div>

按钮的输出没有任何属性...

<div>
  <button>new button</button>
  <div id="myDropdown" aria-expanded="false">
    <ul>content</ul>
  </div>
</div>

【问题讨论】:

    标签: html vue.js vuejs2 vue-component vue-slot


    【解决方案1】:

    使用Scoped Slots

    步骤 1. 在父级中,将旧的 deprecated 槽定位语法 slot="button" 更新为 v-slot 指令:

    Parent.vue

    ...
    <template v-slot:button>                   ✅
      <button>new button</button>
    </template>
    ...
    
    <button slot="button">new button</button>  ❌
    

    如何在 Vue 2.6.0+ 中定位插槽

    第 2 步。 接下来,了解您添加到 &lt;slot&gt; 标记的任何属性绑定都将可用于放置在那里的任何插槽内容(这些称为“插槽道具”):

    Dropdown.vue

    <slot name="button" :aria-haspopup="true">
    

    第 3 步。 Vue 自动创建一个包含第 2 步中的每个绑定的对象,并将其传递给 v-slot 表达式,即下面的 slotProps。然后,您可以使用特殊的 v-bind="" 语法将所有这些绑定传播到按钮上:

    Parent.vue 更新

    <template v-slot:button="slotProps">
      <button v-bind="slotProps">new button</button>
    </template>
    

    这是一个演示,但遗憾的是,当您使用 kebab-case 属性执行此操作时,它需要使用两个连字符进行破解。我计划在 Vue GitHub 存储库中为此提交一个问题。

    Vue.component('dropdown', {
      template: `
      <div>
        <slot name="button" aria--haspopup="true">
          <button aria-haspopup="true">Default Button</button>
        </slot>
        <div id="name" :aria-expanded="expanded">
          <slot />
        </div>
      </div>`,
      data() {
        return {
          expanded: true
        }
      }
    });
    
    new Vue({
      el: "#app",
    });
    .aria-haspopup {
      background: orange;
    }
    <div id="app">
      <dropdown>
        <template v-slot:button="slotProps">
          <button v-bind="slotProps">new button</button>
        </template>
        <ul>content</ul>
      </dropdown>
    </div>
    
    <script src="https://unpkg.com/vue"></script>

    【讨论】:

    • 嗨,谢谢你的详细回答,但如果你检查你的代码 sn-p aria 属性 'aria-haspopup' 丢失。我的意图只是在插槽上放置一些属性,而不增加更多复杂性。所以我想我将只解析第一个按钮的 $el 并通过 js 放置属性。
    • 我更新了演示,我把问题误读为一个类而不是一个属性。它工作得很好......除了带有连字符的属性,所以我向 Vue repo 提交了一个问题。我会留下答案,希望他们能修复它(我在演示中展示了一个解决方法)。
    猜你喜欢
    • 2021-02-27
    • 2020-04-22
    • 2020-11-15
    • 2019-07-08
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多