Skip to content

Commit

Permalink
fix: tabs not update, close #5056
Browse files Browse the repository at this point in the history
  • Loading branch information
tangjinzhou committed Dec 20, 2021
1 parent 5cc1bd7 commit 02e6fec
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions components/tabs/src/Tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import type {
Tab,
} from './interface';
import type { CSSProperties, PropType, ExtractPropTypes } from 'vue';
import { defineComponent, computed, onMounted, watchEffect, camelize } from 'vue';
import { ref, defineComponent, computed, onMounted, watchEffect, camelize } from 'vue';
import { flattenChildren, initDefaultProps, isValidElement } from '../../_util/props-util';
import useConfigInject from '../../_util/hooks/useConfigInject';
import useState from '../../_util/hooks/useState';
Expand Down Expand Up @@ -181,19 +181,24 @@ const InternalTabs = defineComponent({
});

// ====================== Active Key ======================
const [mergedActiveKey, setMergedActiveKey] = useMergedState<Key>(() => props.tabs[0]?.key, {
// use activeKey & mergedActiveKey to control
// https://github.com/vueComponent/ant-design-vue/issues/5056
const [activeKey] = useMergedState<Key>(() => props.tabs[0]?.key, {
value: computed(() => props.activeKey),
defaultValue: props.defaultActiveKey,
});
const mergedActiveKey = ref<Key>();
const [activeIndex, setActiveIndex] = useState(() =>
props.tabs.findIndex(tab => tab.key === mergedActiveKey.value),
);

watchEffect(() => {
let newActiveIndex = props.tabs.findIndex(tab => tab.key === mergedActiveKey.value);
let newActiveIndex = props.tabs.findIndex(tab => tab.key === activeKey.value);
if (newActiveIndex === -1) {
newActiveIndex = Math.max(0, Math.min(activeIndex.value, props.tabs.length - 1));
mergedActiveKey.value = props.tabs[newActiveIndex]?.key;
} else {
mergedActiveKey.value = activeKey.value;
}
setActiveIndex(newActiveIndex);
});
Expand Down Expand Up @@ -221,9 +226,11 @@ const InternalTabs = defineComponent({
// ======================== Events ========================
const onInternalTabClick = (key: Key, e: MouseEvent | KeyboardEvent) => {
props.onTabClick?.(key, e);

setMergedActiveKey(key);
props.onChange?.(key);
const isActiveChanged = key !== mergedActiveKey.value;
if (isActiveChanged) {
mergedActiveKey.value = key;
props.onChange?.(key);
}
};

useProvideTabs({
Expand Down

0 comments on commit 02e6fec

Please sign in to comment.