Tab selection programmatically in Q-tabs
-
I discovered something that may be worth sharing (or please comment if I’m missing something).
When a tab is selected programmatically, Q-tabs automatically scrolls the tab bar if needed to ensure the selected tab is visible. This is an important feature.
However, if I add a new tab and then select it, it does not scroll into view. To correct this, I found that adding a delay before selecting the new tab solves it.To illustrate this, I made a small code-sandbox example…
https://codesandbox.io/s/scrolltest-with-tabs-87ylg?file=/src/layouts/MainLayout.vueComments welcome. Still learning Quasar and I appreciate all the help I get on this forum!
-
Looks like a bug to me. In my experience if
setTimeout
solves a bug something is wrong with the code. -
@dobbel Can you look at my code and see if you can spot a bug? Or did you mean a bug in Quasar?
-
I changed your code a bit and created an alternative solution:
https://codesandbox.io/s/scrolltest-with-tabs-forked-x09yh?file=/src/layouts/MainLayout.vue
- the selecting of newly added tabs is now handled in the Tabs component instead of the Mainlayout.
- changed the watched variable in Tabs component from selectedTabs to tabs.
- instead of using
setTimeout
with an arbitrary value, I usedVue.nextTick()
to select the new tab and successfully scroll to the new q-tab. - For simplicity I removed the ability to change the select tab from the parent of the Tabs component( MainLayout).
Apparently this is one of the situations that you need to wait for the DOM to update in order to apply updates to the DOM again. So no bug but I think this is one of the rough sides of reactivity in Vue 2.
In comparison: with good old AngularJS you had the same problem sometimes ( you had to use $scope.$apply() to force the DOM to update in certain situations).
But at least with AngularJs you knew exactly what these situations where that needed to be revolved with forced updates.No idea if Vue 2 has any rules or ways to know beforehand if you need to resort to nextTick().
From: https://vuejsdevelopers.com/2019/01/22/vue-what-is-next-tick/
Sometimes we need to wait for some elements to appear/disappear/be modified in >the DOM. This is when nextTick comes in handy.
-
@dobbel Thanks. That’s a much neater solution!
In the real app, tabs are added via vuex, but your approach will still work with that - just need to watch the store’s tablist.