首页 > 解决方案 > Vue 3选项卡不呈现childeren

问题描述

我似乎无法让我的 vue 标签组件工作,由于某种原因它没有渲染子组件。我的代码中缺少什么?

选项卡.vue

<template>
    <nav>
        <ul class="tabs">
            <li v-for="(tab, index) in tabs" :key="index" :class=" active === index ? 'active': '' ">
                <a href="" class="tab__link" @click="selectTab(index)">
                     {{ tab.props.title }}
                </a>
            </li>
        </ul>
        <div class="tabs__content">
            <slot/>
        </div>
    </nav>
</template>

<script>
    import { provide, computed, ref } from "vue";

    export default {
        name: 'tabs',
        props: {
            modelValue: {
                type: [String, Number],
            },
        },
        emits: ["update:modelValue"],
        setup(props, { slots, emit }) {
            const active = computed(() => props.modelValue);
            const tabs = ref([]);

            function selectTab(tab) {
                emit("update:modelValue", tab);
            }

            provide("tabsState", {
                active,
                tabs,
            });

            return {
                tabs,
                active,
                selectTab,
            };
        }
    }    
</script>

选项卡.vue

<template>
    <div v-if="isActive">
        <slot />
    </div>
</template>

<script>
    import { computed, inject, watchEffect, getCurrentInstance } from "vue";

    export default {
        name: 'tab',
        props: {
            title: String,
        },
        setup(props) {
            const instance = getCurrentInstance();
            const { tabs, active } = inject("tabsState");

            const index = computed(() => {
                tabs.value.findIndex((target) => target.uid === instance.uid)
            });

            const isActive = computed(() => {
                index.value === active.value
            });

            watchEffect(() => {
                if (index.value === -1) {
                    tabs.value.push(instance);
                }
            });

            return {
                isActive,
            };
        },
    }
</script>

页面.vue

<template>
    <tabs v-model="active">        
        <tab title="tab-one"> 
            Tab 1
        </tab> 
        <tab title="tab-two"> 
            Tab 2
        </tab> 
    </tabs>      
</template>

<script>

import tabs from '../../Components/Navigation/Tabs'
import tab from '../../Components/Navigation/Tab'
import { ref } from "vue";

export default {
    components: {
      tabs,
      tab
    },
    setup() {
        const active = ref(1);

        return { active };
    }
}
</script>

标签: vuejs3

解决方案


推荐阅读