Vue 3 如何获取有关 $children 的信息 [英] Vue 3 how to get information about $children
问题描述
这是我在 Tabs 组件中使用 VUE 2 的旧代码:
created() {this.tabs = this.$children;}
标签:
<标签标题=标签标题">....</Tab><标签标题=标签标题">....</Tab></Tabs>
VUE 3:如何使用组合 API 在 Tabs 组件中获取有关儿童的一些信息?获取长度,迭代它们,并创建标签页眉,......等等?有任何想法吗?(使用组合 API)
这是我的 Vue 3 组件.我使用提供来获取子 Tab
组件中的信息.
<div class="tabs"><div class="tabs-header">
<插槽></插槽>
</模板><script lang="ts">从vue"导入{defineComponent、reactive、provide、onMounted、onBeforeMount、toRefs、VNode};接口 TabProps {标题:字符串;}导出默认defineComponent({名称:标签",设置(_,{插槽}){const 状态 = 反应性({选择索引:0,tabs: [] 作为 VNode 标签组件:导出默认defineComponent({名称:标签",设置() {常量索引 = ref(0);const isActive = ref(false);const tabs = 注入(TabsProvider");手表(() =>tabs.selectedIndex,() =>{isActive.value = index.value === tabs.selectedIndex;});onBeforeMount(() => {index.value = tabs.count;tabs.count++;isActive.value = index.value === tabs.selectedIndex;});返回 {index, isActive};}});<div class="tab"v-show=isActive"><插槽></插槽>
This my old code with VUE 2 in Tabs component:
created() {
this.tabs = this.$children;
}
Tabs:
<Tabs>
<Tab title="tab title">
....
</Tab>
<Tab title="tab title">
....
</Tab>
</Tabs>
VUE 3: How can I get some information about childrens in Tabs component, using composition API? Get length, iterate over them, and create tabs header, ...etc? Any ideas? (using composition API)
This is my Vue 3 component now. I used provide to get information in child Tab
component.
<template>
<div class="tabs">
<div class="tabs-header">
<div
v-for="(tab, index) in tabs"
:key="index"
@click="selectTab(index)"
:class="{'tab-selected': index === selectedIndex}"
class="tab"
>
{{ tab.props.title }}
</div>
</div>
<slot></slot>
</div>
</template>
<script lang="ts">
import {defineComponent, reactive, provide, onMounted, onBeforeMount, toRefs, VNode} from "vue";
interface TabProps {
title: string;
}
export default defineComponent({
name: "Tabs",
setup(_, {slots}) {
const state = reactive({
selectedIndex: 0,
tabs: [] as VNode<TabProps>[],
count: 0
});
provide("TabsProvider", state);
const selectTab = (i: number) => {
state.selectedIndex = i;
};
onBeforeMount(() => {
if (slots.default) {
state.tabs = slots.default().filter((child) => child.type.name === "Tab");
}
});
onMounted(() => {
selectTab(0);
});
return {...toRefs(state), selectTab};
}
});
</script>
Tab component:
export default defineComponent({
name: "Tab",
setup() {
const index = ref(0);
const isActive = ref(false);
const tabs = inject("TabsProvider");
watch(
() => tabs.selectedIndex,
() => {
isActive.value = index.value === tabs.selectedIndex;
}
);
onBeforeMount(() => {
index.value = tabs.count;
tabs.count++;
isActive.value = index.value === tabs.selectedIndex;
});
return {index, isActive};
}
});
<div class="tab" v-show="isActive">
<slot></slot>
</div>
这篇关于Vue 3 如何获取有关 $children 的信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!