The route as the current step
Keep the step in the URL with Vue Router or Nuxt, in both directions.
The step option makes the flow follow a value that lives somewhere else. Pass
the options as a function so they are read again when the route changes.
<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
// Outside `pages/`: Nuxt turns every file in that folder into a route.
import { checkout } from "~/flows/checkout";
const route = useRoute();
const router = useRouter();
const stepper = checkout.useStepper(() => ({
linear: true,
// The route moves (a link, the back button): the flow follows.
step: route.params.step as string,
// The flow moves: push the new step.
onChange: (snapshot) => {
if (snapshot.step !== route.params.step) {
router.push({ params: { step: snapshot.step } });
}
},
// The route asks for a step the flow cannot be on: correct it without a history entry.
onInvalidStep: (current) => router.replace({ params: { step: current } }),
}));
</script>- Following the route is a
goTo. Withlinear, a deep link cannot open a step before the ones in front of it are complete. Withoutlinear, any step can be opened, as withgoTo. - The
guardruns when the route changes after the page is mounted. It does not run for the step the page first loads on. onInvalidStepis called for unknown ids, for stepslineardoes not allow yet and for route changes the guard refused.- On the server the flow starts on the route's step when that is allowed, and no callback runs until the page is mounted.
- Under
<KeepAlive>(<RouterView v-slot="{ Component }"><KeepAlive>or Nuxt'skeepalive), a cached page stops following the route while another page is shown, so it never rewrites that page's URL. When it is shown again it follows the route as it is then.
A query parameter works the same way: read route.query.step and write it with
router.push({ query: { step } }).
Edit on GitHub
Last updated on