Issue
I have some tabs that are used for my apps navigation. Each tab displays a different data table and is a different route. However, when a user selects some filters and an api call is made, the tab that is currently selected goes to the default and doesn't stay with the current tab after the data is loaded.
How can I keep the current tab selected after an api call to the backend?
I thought about either session or localStorage, but I'm not sure how I would target the checked attribute on the input field and how to restore it after the reload/refresh.
Here's some a sample of my template code with the tabs:
<div class="tab">
<input
type="radio"
checked
name="css-tabs"
id="tab-1"
class="tab-switch"
/>
<label
for="tab-1"
class="tab-label"
@click="$router.push('/route-1')"
>
Route - 1</label
>
<div class="tab-content">
<router-view :key="$route.path" />
</div>
</div>
<div class="tab">
<input type="radio" name="css-tabs" id="tab-2" class="tab-switch" />
<label
for="tab-2"
class="tab-label"
@click="$router.push('/route-2')"
>
Route-2</label
>
<div class="tab-content">
<router-view :key="$route.path" />
</div>
</div>
Solution
I solved this by refactoring the tab code in the template
<div class="tabs">
<div class="tab" v-for="(tab, index) in tabs" :key="tab.id">
<input
type="radio"
:name="tab.name"
:id="tab.id"
class="tab-switch"
:checked="tab.checked"
@change="updatedActiveTab(index)"
/>
<label
:for="tab.id"
class="tab-label"
@click="$router.push(tab.path)"
>
{{ tab.label }}</label
>
<div class="tab-content">
<router-view :key="$route.path" />
</div>
And then created a function to change the checked property to the selected tab as true and all others to false.
tabs.value.forEach((elem, idx) => {
elem.checked = idx == index;
});
sessionStorage.tabs = JSON.stringify(tabs.value);
}
Answered By - Nathan Azevedo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.