Skip to content

Instantly share code, notes, and snippets.

@clmrb
Created February 4, 2026 13:52
Show Gist options
  • Select an option

  • Save clmrb/9a9ee0589a84efbb85482b45d9c5b277 to your computer and use it in GitHub Desktop.

Select an option

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
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