【问题标题】:Is there way to access <slot /> data in script tag?有没有办法访问脚本标签中的 <slot /> 数据?
【发布时间】:2019-08-29 11:48:07
【问题描述】:

我使用 slot HTML 元素将传递的数据从父组件打印到子组件。我想在子组件内的脚本标记内的方法中使用数据。有没有办法访问槽数据并将其分配给数据方法中的对象?

我的父组件

<template>
  <div class="footer">
      <app-footer>Contacts</app-footer>
  </div>
</template>

我的子组件

<template>
  <div class="child">
      <slot />
  </div>
</template>

【问题讨论】:

    标签: vue.js vue-component


    【解决方案1】:

    如果您将您的插槽包装在一个元素中,您可以使用ref 标签来获取对包装器的引用。不支持直接引用槽,因为它可以是单个元素,也可以是多个元素。

    例如

    <div class='wrap' ref='wrap'>
      <slot />
    </div>
    

    在js中;

    this.$refs.wrap // contains an HTMLElement
    this.$refs.wrap.childNodes // contains (all) the element(s) in the wrap / slot
    

    您还可以使用this.$slotsthis.$children 来获取您放置在插槽中的vue 组件。

    【讨论】:

    • 我尝试使用console.log(this.$refs.wrap)在控制台中查看槽值,它显示一个未定义的值。
    • 哎呀在包装上设置了slot 属性,而不是ref。示例现已修复。
    • 嗯,这很有帮助。现在更有意义了。
    【解决方案2】:

    您可以简单地将该数据绑定到父组件上,并将其作为子组件的 prop 获取

    <template>
      <div class="footer">
          <app-footer :data="data">Contacts</app-footer>
      </div>
    </template>
    
    <template>
      <div class="child">
          <slot />
      </div>
    </template>
    
    export default {
     props: {
      data: Object // <- here you receives parent data
     }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-22
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      • 2011-10-23
      • 1970-01-01
      • 2020-04-17
      • 2015-05-12
      • 1970-01-01
      相关资源
      最近更新 更多