【发布时间】:2019-02-20 06:00:41
【问题描述】:
假设我想创建一个多层组件以供重复使用,例如 'Tab' Ui。
所以使用开发者可以这样写:
<tabs>
<tab label="My First Tab">
Content for first tab which could contain components, html, etc.
</tab>
<tab label="My Second Tab">
More Content
</tab>
</tabs>
基本上,他们会以这样一种方式使用 Tabs 和 Tab 组件,以至于我不知道开发人员将在 Tabs 中使用多少个 Tab 组件。如何访问选项卡组件,例如,按选项卡 UI 功能显示和隐藏它们?
我尝试过使用this.$children 和this.slots.default,但实际上无法访问选项卡数据来显示和隐藏它。公平地说,我正在用 Typescript 写作,因此问题可能会更加困难。
类似:
<template>
<div class="tabs">
<slot /> <!-- Location of the Tab's -->
</div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
@Component({
...
})
export default class Tabs extends Vue {
public tabs: any[] = [];
public created() {
this.tabs = this.$slots.default;
// this.tabs is a set of VNode's,
// I can't figure out how to access the components
// I see a prop 'componentInstance' but when I try to
// access it, it says undefined
// this.select(0);
let tab = this.tabs.find((obj: any, index: number) => {
return index === 0;
}); // tab is undefined :(
}
public select(index: number) {
(this.$slots.default[index] as any).show = true;
// Accessing Vnode instead of Component :(
// this.$children[0]["show"] = true; // Read only :(
// this.tabs[index].show = true; // blerrggg :(
// Vue.nextTick();
}
}
</script>
我在 Vue 中查看了一些用于 Tabs 的 GitHub 库,逻辑似乎非常复杂。我假设存在插槽/子组件,有一种更直接的方法来访问子组件。也许这对我来说过于乐观了。
如果您不知道子槽中有多少子槽(即您没有在父组件中明确编写它们),任何人都知道如何访问、传递或更改子槽中的数据?
【问题讨论】:
标签: typescript vuejs2