I am using PrimeVue V3 TabView with composition API.
Inside each tab I have a form and I want to trigger form validation before switching tabs. So I need to interrupt the tab change, do something (form validation), and then conditionally proceed to the clicked tab.
The TabView docs show 3 events: update:activeIndex
, tab-change
, and tab-click
. But as far as I can tell, all of those are triggered after changing tabs, not before.
Any idea how to go this working?
I found a similar question and answer based on the old Options API but I cannot get it working for Vue 3 Composition API.
Here is a live reproduction on stackblitz.
<template>
<TabView
v-model:activeIndex="activeIndex"
@tab-change="handleTabChange"
@tab-click="handleTabClick"
>
<TabPanel header="Opening Hours"> Opening hours form goes here </TabPanel>
<TabPanel header="Contacts"> Contacts form goes here </TabPanel>
</TabView>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import type { TabViewChangeEvent, TabViewClickEvent } from 'primevue/tabview';
const activeIndex = ref();
const handleTabClick = async (event: TabViewClickEvent) => {
console.log('handleTabClick', event);
const nextTabIndex = event.index;
const isValid = false; // Simulated form validation
if (isValid) {
// Form is valid, continue with the tab change
console.log('form valid');
activeIndex.value = nextTabIndex;
} else {
// Form is invalid, do nothing (don't change tabs)
console.log('form invalid');
}
};
const handleTabChange = async (event: TabViewChangeEvent) => {
console.log('handleTabChange', event);
const nextTabIndex = event.index;
const isValid = false; // Simulated form validation
if (isValid) {
// Form is valid, continue with the tab change
console.log('form valid');
activeIndex.value = nextTabIndex;
} else {
// Form is invalid, do nothing (don't change tabs)
console.log('form invalid');
}
};
</script>
2
Answers
This version does not require changing of the inner
onTabClick
method.See live reproduction here.
I just made the old Options API answer workable for you
Here is the code