Home > other >  Reusable Vuejs 3 tab component does not switch correctly between tabs
Reusable Vuejs 3 tab component does not switch correctly between tabs

Time:06-23

While creating a reusable tabs component in Vuejs 3 with Typescript and the Composition api, i've run into a strange behavior where the content of the first tab isn't shown when it is selected after selecting another tab.

The click on the tab is registered in the changeTab() method, but the selected Tab component isn't rendered. I assume the issue has something to do with the state change of the Tabs component not being registered, so the meta-component in turn isn't rerendered but I can't figure out why.

I've created a demo to illustrate the issue:

SFC playground demo

Here is the script and template section of the Tabs.vue component:

<script setup lang="ts">
import { ref, useSlots, onMounted } from "vue"
const tabs = ref([])
const currentTab = ref()
const slots = useSlots()

onMounted(() => {
    if (slots !== null) {
        slots.default?.().map((child) => {
            tabs.value.push(child)
        })
            currentTab.value = tabs.value[0]
    }
})
  
const changeTab = (tab: object) => {
    currentTab.value = tab
}
</script>
<template>
    <ul>
        <li v-for="(tab, index) in tabs" :key="index" @click="changeTab(tab)">
            {{ index   1 }}
        </li>
    </ul>
    <component :is="currentTab"></component>
</template>

CodePudding user response:

Your component should have a key too to make Vue render it correctly.

// You should save currentIndex somewhere in your script
<component :key="currentIndex" :is="currentTab"></component>
  • Related