rcbyr / keen-slider

The HTML touch slider carousel with the most native feeling you will get.
https://keen-slider.io/
MIT License
4.57k stars 210 forks source link

fix(vue): slider not visible after resize & activation in KeepAlive #421

Open mathiasstamm opened 1 month ago

mathiasstamm commented 1 month ago

This PR fixes a small but obscure bug which occurs when the window is resized while a keen-slider is hidden BUT cached by vue's KeepAlive.

KeepAlive can be used when a component is being rendered dynamically (using <component />), but you want it to remain cached ("alive") while another component is being rendered. A component may not receive all updates and events while being hidden/cached.

Here's how the bug is reproduced:

  1. Dynamically render a keen-slider instance in a component which is being cached using KeepAlive.
  2. Dynamically render another component, hiding the original one holding the slider.
  3. Resize the window.
  4. Re-render the original (cached) component with the slider.

The slider is now effectively invisible, because all slides are translated to 0, 0, 0 with a width of 0.25px. This is likely because the slider wasn't being alerted of required events whilst hidden. As soon as the window is resized again, it fixes itself.

This does not happen if the window isn't resized before it's re-rendered.

Here's how the bug can be fixed (this PR):

Vue offers the onActivated and onDeactivated lifecycle hooks. They're called if a component gets hidden (deactivated) or shown (activated) in a KeepAlive component. Calling the slider's update() function in the onActiavted hook fixes the slider as soon as it appears, making it work flawlessly with KeepAlive.

onActivate is only called if the component is actually inside a KeepAlive.

This is actually my first real contribution to a public repository, I hope I'm doing this right :)