Skip to content

Commit 944b431

Browse files
committed
Introduce controlled mode for Tabs component:
- Allows parent component to control which tab is active
1 parent 575d86d commit 944b431

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

src/components/Tabs/Tabs.vue

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,16 @@ export default {
6969
return false;
7070
},
7171
},
72+
/**
73+
* Passing a string value will enable `controlled mode`.
74+
* In this mode, the `activeTab` is used by the parent component to control which tab is active.
75+
*
76+
* When `null`, the component will manage the active tab internally.
77+
*/
78+
activeTab: {
79+
type: [String, null],
80+
default: null,
81+
},
7282
},
7383
data() {
7484
return {
@@ -83,7 +93,11 @@ export default {
8393
* @param {String} tabId
8494
*/
8595
setCurrentTab(tabId) {
86-
this.currentTab = tabId;
96+
if (this.activeTab === null) {
97+
this.currentTab = tabId;
98+
} else {
99+
this.$emit('update:activeTab', tabId);
100+
}
87101
this.$nextTick(() => {
88102
$(this.$refs['button' + tabId]).focus();
89103
this.updateUrl();
@@ -155,6 +169,14 @@ export default {
155169
currentTab(newVal, oldVal) {
156170
this.tabs.forEach((tab) => tab.isActive(tab.id === newVal));
157171
},
172+
/**
173+
* In controlled mode, when the `activeTab` prop changes, update the current tab.
174+
*/
175+
activeTab(newVal) {
176+
if (newVal !== null) {
177+
this.currentTab = newVal;
178+
}
179+
},
158180
},
159181
provide() {
160182
return {
@@ -176,7 +198,11 @@ export default {
176198
/**
177199
* Set the tab to view when loaded
178200
*/
179-
this.currentTab = this.defaultTab || this.tabs[0].id;
201+
const initialTab =
202+
this.activeTab !== null
203+
? this.activeTab
204+
: this.defaultTab || this.tabs[0]?.id || '';
205+
this.currentTab = initialTab;
180206
181207
/**
182208
* Listen for global 'open-tab' events and open the correct tab when called

0 commit comments

Comments
 (0)