Routing and State in Vue.js
Routing and State is the eighth chapter of the free Vue.js tutorial. It turns a single page into a multi-page app and gives it shared, app-wide state.
What each lesson covers:
- Vue Router Basics:
createRouter(), history modes,RouterLinkandRouterView, params and query,useRoute()anduseRouter(), matching patterns, a 404 page, nested routes, named views, redirects and aliases. - Navigation Guards and Advanced Routing: Global, per-route and in-component guards, typed route meta and an auth guard, fetching before or after navigation, scroll behaviour, lazy routes and focus after navigation.
- State Management with Pinia: When to use a store, option and setup stores, getters and actions,
storeToRefs(),$patchand reset, async actions, stores together,$subscribe,$onActionand plugins.
Every box runs real Vue 3 in your browser. Pick TypeScript or JavaScript in the top bar, and every box switches. Each lesson ends with exercises that check what your app does, not how your code is written.
Lessons in this section
- Vue Router Basics
Installing Vue Router, createRouter() and history modes, routes, RouterLink and RouterView, active link classes, useRouter() and useRoute(), params and query, optional, repeatable and pattern params, nested routes, named views, route props, named routes, redirects, aliases, a 404 page, and push, replace and go.
- Set up Vue Router with routes, RouterLink and RouterView
- Read params and query with useRoute() and move with useRouter()
- Match optional, repeatable and pattern params and show a 404 page
- Build nested routes, named views, redirects and aliases
- Navigation Guards and Advanced Routing
Global guards (beforeEach, beforeResolve, afterEach), per-route beforeEnter, in-component onBeforeRouteLeave and onBeforeRouteUpdate, typed route meta, an auth guard with a redirect back, fetching data before or after navigation, scroll behaviour, lazy-loaded routes and moving focus after navigation.
- Allow, cancel or redirect navigation with global, per-route and in-component guards
- Protect pages with typed route meta and an auth guard
- Load data before or after navigation and react to param changes
- Lazy-load routes, control scrolling and move focus after navigation
- State Management with Pinia
Local vs shared state and when to use a store, createPinia(), option stores and setup stores, state, getters and actions, async actions with errors, storeToRefs(), $patch, $reset and resetting setup stores, stores using stores, stores outside components, $subscribe, $onAction, persistence and Pinia plugins.
- Decide when state belongs in a store
- Write option stores and setup stores with state, getters and actions
- Use stores safely with storeToRefs(), $patch() and reset
- Watch stores with $subscribe() and $onAction() and persist them