Shared Vue component across routes with animations
Why?
It’s quite common you might have a same component used in different routes (pages) with a bit different sizes and positions. Sometimes you might want to animate them when user navigates between routes to provide a smooth UX. While such animation is common to be seen in native apps, it’s could be a bit challenging to do it in Web.
Vue’s component structure is presented as a tree, and the child components are in different branches with their own instances. Meaning when users navigate between routes, the components are not shared across routes.
By that means you can’t directly animate the changes because they are in two different instances. The good news is, there is a technique called FLIP to enumerate the transitions between them.
However, FLIP only solves the problem of transitions, the components are still not the same. During the navigation, the internal state of the component will lost.
Thus I started this new approach Starport to experiment with a better solution to fit this requirement.
How?
So since we can’t share the components across different branches in the component tree, we could actually hoist them to the root so they become independent from the routes.
To allow each page to still have control of the components, we introduced a Proxy component to present the expected size and position of that component. The proxy will pass the props and position infomation to the actual component and let it “fly over” the proxy with animations.
When the transition ends and it arrived to the expected position, it will then “land down” to the actual component using the <Teleport/> component.
With this “landing” mechanism, the DOM tree will be preserved as what you will have with the original tree structure. When navigating to another route, the component then will “lift off” back to the floating state, “fly” to the new proxy’s position and “land” again.
This is very similar to Terran’s Buildings in StarCraft (able to leave the ground and fly to new locations). It’s also the inspiration source of the project name Starport.
Install
⚗️ Experimental
Vue Starport only works for Vue 3
Usage
At root App.vue, add <StarportCarrier> component from vue-starport at the end of the dom. <StarportCarrier> will be the place to store all the flying components.
<div class="highlight highlight-text-html-basic position-relative overflow-auto" data-snippet-clipboard-copy-content="<script setup>
import { StarportCarrier } from 'vue-starport'
</script>
<template>
<RouterView />
<StarportCarrier />
</template>”>
<script setup>
import { StarportCarrier } from ‘vue-starport’
</script>
<template>
<RouterView />
<StarportCarrier /> <!– here –>
</template>