I’m currently making a nav bar. I create an array storing the info of the tabs in the nav bar.
JavaScript
x
8
1
tabs: [
2
{ name: 'All',id: "dash.courses.all", to: 'all', current: false },
3
{ name: 'Self-paced Learning',id: "dash.courses.oneToOneClasses", to: 'selfPacedLearningComp', current: false },
4
{ name: '30 Days Challenge',id: "dash.courses.selfPacedLearningComp", to: 'thirtyDaysChallenge', current: false },
5
{ name: 'Group Classes',id: "dash.courses.groupClasses", to: 'groupClasses', current: false },
6
{ name: '1-to-1 Classes',to: "dash.courses.thirtyDaysChallenge", to: 'oneToOneClasses', current: false },
7
]
8
When a new route is clicked it updates the newly clicked tab to allow the current property to be true.
How would you change the previous nav item to false. As currently they all change to true one by one as they are clicked.
I think if I store a value as previous
JavaScript
1
15
15
1
setCurrent(tab)
2
{
3
4
let newArr = this.tabs.map(obj => {
5
if (obj.id === tab) {
6
return {obj, current: true};
7
}
8
9
return obj;
10
})
11
this.tabs = newArr
12
console.log(newArr)
13
}
14
},
15
This is what i’ve got atm, it has to go around 3 routes ahead till the one before vanishes…
JavaScript
1
50
50
1
<script>
2
export default {
3
components: {
4
},
5
data()
6
{
7
return {
8
prevTab: null,
9
tabs: [
10
{ name: 'All',id: "dash.courses.all", to: 'all', current: false },
11
{ name: 'Self-paced Learning',id: "dash.courses.oneToOneClasses", to: 'selfPacedLearningComp', current: false },
12
{ name: '30 Days Challenge',id: "dash.courses.selfPacedLearningComp", to: 'thirtyDaysChallenge', current: false },
13
{ name: 'Group Classes',id: "dash.courses.groupClasses", to: 'groupClasses', current: false },
14
{ name: '1-to-1 Classes',to: "dash.courses.thirtyDaysChallenge", to: 'oneToOneClasses', current: false },
15
]
16
}
17
},
18
methods: {
19
setCurrent(tab)
20
{
21
this.prevTab = this.$route.name
22
let newArr = this.tabs.map(obj => {
23
if (obj.id === tab) {
24
return {obj, current: true};
25
}
26
if(obj.id === this.prevTab) {
27
return {obj, current: false}
28
}
29
30
return obj;
31
})
32
console.log('previous ',this.prevTab)
33
console.log('route name', this.$route.name)
34
this.tabs = newArr
35
}
36
},
37
mounted()
38
{
39
this.prevTab = this.$route.name
40
const newArr = this.tabs.map(obj => {
41
if (obj.id === this.$route.name) {
42
return {obj, current: true};
43
}
44
45
return obj;
46
});
47
this.tabs = newArr
48
}
49
}
50
Advertisement
Answer
Create a watcher on the route name
JavaScript
1
10
10
1
watch: {
2
"$route.name": {
3
handler(routeName) {
4
this.tabs.forEach((tab) => (tab.current = routeName === tab.name));
5
},
6
// force eager callback execution
7
immediate: true,
8
},
9
}
10
Usually you can just use the watcher routeName
value above to run whatever side effect you want but if tracking current
on each tab is really necessary the above code will get the job done.