【问题标题】:Vue js v3 component does not have access to $children anymore. How can we get a component children?Vue js v3 组件不再有权访问 $children。我们怎样才能得到一个子组件?
【发布时间】:2020-10-16 18:56:37
【问题描述】:

使用 Vue 2,我们可以使用 this.$children 来获取组件槽中的所有子组件。但是对于 Vue 3,这是不可能的。而且我找不到任何关于替代方案或解决方法的信息!

那么,有人可以帮忙吗? :)

我想要实现的是:

拥有一个名为 TabsView 的组件

我想这样使用它:

<tabs-view>
  <tabs-title target="tab1">Title1</tabs-title>
  <tab-content name="tab1">...</tab-content>

  <tabs-title target="tab2">Title2</tabs-title>
  <tab-content name="tab2">...</tab-content>
<tabs-view>

我想要 TabsView 组件中的所有逻辑。所以这就是为什么我想在其中获得 $children 。所以我可以使用子组件的值来构建选项卡。

因为我将使用相同的方法在不同的许多地方构建标签。而且我不想用 refs 复制逻辑。除非有办法使用 refs 做到这一点,而无需将相同的逻辑移动到我使用组件的每个地方

【问题讨论】:

  • 你为什么不使用 refs 来代替?你想做什么?
  • @GuillaumeF。很好的建议,我现在使用 refs 作为“解决方法”,但我想要实现的场景类似于选项卡组件。如: 12 和 tabs 组件内部我想获取给定的 tab 实例并控制它们。
  • &lt;tabs&gt; &lt;tab ref="myTabRef"&gt;1&lt;/tab&gt; &lt;tab ref="myTabRef"&gt;2&lt;/tab&gt;&lt;/tabs&gt; 然后在tabs 组件中以this.$refs.myTabRef 访问它。这将为您提供两个选项卡组件的数组。
  • 好的,我会用一个例子来更新这个问题:D

标签: vue.js vuejs3


【解决方案1】:

您可以使用this.$el.parentElement.children 来获取 DOM 元素,但这不会为您提供组件。 this:this.$.subTree.children 会给你孩子,其中包括 DOM 元素和组件。

但此功能可能出于某种原因被隐藏,所以如果 @Guillaume F 想让您考虑替代解决方案,我会听取他的建议。

示例:

const app = Vue.createApp({
  data() {
    return {
      color: null
    }
  },
  mounted() {
    const children = this.$.subTree.children
    console.log(children.map(c => c.type))
  }
})

app.component('tabs-title', {
  template: '<h1>TITLE: <slot></slot></h1>'
})
app.component('tab-content', {
  template: '<p>TAB: <slot></slot></p>'
})

app.mount('#app')
<script src="https://unpkg.com/vue@3.0.0/dist/vue.global.prod.js"></script>
<div id="app">
  <tabs-title target="tab1">Title1</tabs-title>
  <tab-content name="tab1">...</tab-content>

  <hr/> <!-- will return string as type -->
  <tabs-title target="tab2">Title2</tabs-title>
  <tab-content name="tab2">...</tab-content>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2011-04-11
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2015-12-15
    • 2015-06-08
    相关资源
    最近更新 更多