Created
February 4, 2026 13:52
-
-
Save clmrb/9a9ee0589a84efbb85482b45d9c5b277 to your computer and use it in GitHub Desktop.
Vue3/Vuetify3 Javascript composable to detect when current component is inside an active vuetify tab
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { getCurrentInstance, watch } from 'vue'; | |
| function findComponentInstanceByName(instance, name) { | |
| if (!instance?.parent) { | |
| console.warn(`No parent component found with name "${name}"`); | |
| return null; | |
| } | |
| if (instance.parent.type.name !== name) { | |
| return findComponentInstanceByName(instance.parent, name); | |
| } | |
| return instance.parent; | |
| } | |
| /** | |
| * Execute a callback when the component is inside an active vuetify tab | |
| * @param callback {() => void} callback to execute | |
| * @param options {Parameters<import('vue').watch>[2]} watch options | |
| */ | |
| export const onTabActive = (callback, options = { immediate: true }) => { | |
| const instance = getCurrentInstance(); | |
| const vTabsWindowItem = findComponentInstanceByName(instance, 'VTabsWindowItem'); | |
| const vTabsWindow = findComponentInstanceByName(vTabsWindowItem, 'VTabsWindow'); | |
| if (!vTabsWindow || !vTabsWindowItem) { | |
| return console.warn('onTabActive must be used inside a VTabsWindowItem/VTabsWindow component'); | |
| } | |
| watch(() => vTabsWindow.ctx.modelValue, (currentValue) => { | |
| if (currentValue === vTabsWindowItem.ctx.value) { | |
| callback(); | |
| } | |
| }, options); | |
| }; | |
| // Used in this context: | |
| // <v-tabs-window v-model="currentTab"><v-tabs-window-item :value="'tab1'"><MyTabComponent /></v-tabs-window-item></v-tabs-window> | |
| // Usage in MyTabComponent script setup | |
| onTabActive(() => console.log('MyTabComponent is active!')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment