MY notebook

Vue Router 3

Published on Nov 30, 2021




Getting Started

  • router-link and router-view
  • steps:
    • define route components
    • define routes
    • create router instance and pass routes to it
    • create and mount the root instance ($mount)
  • we get this.$router (same as importing router) and this.route

Dynamic Route Matching

  • path: ‘/user/:id’ when define routes
  • the dynamic segment (/:id) can be access through this.$
  • also have options like query (if there’s one in the URL) and hash for params
  • we need to watch the $route object OR use beforeRouteUpdate if we want to trigger the lifecycle hooks since vue reuses the same component
  • make sure to move any match all (*) to the end of the declaration
  • the earlier a route is defined, the higher priority it gets
  • the url matched by * can be access through $route.params.pathMatch

Nested Routes

  • component can has its own router-view
  • use children when defining routes to create nested route (/user/:id/:profile)
  • can nest as many layer as needed
  • pass empty path ({path:’ ’, component: UserHome}) if you want to render things at the outlet (/user/:id)

Programmatic Navigation

  • router.push(location, onComplete?, onAbort?), onComplete callbacks execute when all async hooks are resolved, whereas onAbort is for situations like navigated to the same route, or to a different route before current navigation has finished).
    • clicking router-link is the same as calling router.push(…). They add an entry to the history stack
    • can push a string path or location descriptor object (just the path, named route, with query)
    • use path OR params, not both, unless you are using query
  • router.replace(location, onComplete?, onAbort? ) is the same as push but it didn’t add entry to the stack
  • In 3.1.0+, omit onComplete and onAbort and router.push/router.replace will return a Promise
  • router.go(n) go forwards/backwards n steps in the history stack
  • push, replace, go work consistently in all router modes (history, hash, and abstract)

Named Routes

  • can give name when defining routes
  • pass object to to in router-link to access named route OR push one

Named Views

  • give router-view a name so it’s easier to display multiple views
  • pass components when defining routes to display them (and says who is default)

Redirect and Alias

  • pass redirect when defining routes
  • can be string OR named route OR function (for dynamic redirecting)
  • Navigation Guards will not be applied to route that redirects
  • /a with redirect /b means URL will be replaced by /b when visit /a
  • /a with alias /b means URL remains /b but still visiting /a

Passing Props to Route Components

  • pass props when defining routes makes the component easier to reuse and test
  • boolean mode (props:true): route.params will be set as the component props
  • object mode(props:{…}`): as-is. Useful when props are static
  • function mode (props:route=>({query:route.query.q}) would pass {query:’hey’} when hitting /path?q=hey`) allows you to cast parameters, combine static values with route-based values, etc
  • keep it stateless as it’s only evaluated on route changes
  • use wrapper component if need state to define props

HTML5 History Mode

  • hash mode is the default for vie-router, page won’t reload when the URL changes
  • pass mode when defining routes to change mode
  • URL looks normal in history mode
  • add catch-all fallback route to server to properly configure server


  • ways: global, pre-route, in-component
  • params or query changes won’t trigger enter/leave navigation guards
  • global guards:
    • router.beforeEach: navigation remains pending before all hooks get resolved, confirmed when done
    • router.beforeResolve: resolve guards is called right before the navigation is confirmed AND after all in-component guards and async route components are resolved
    • router.afterEach don’t get a next function and can not affect the navigation
  • guard function arguments
    • to: Route object
    • from: current Route
    • next: Function to resolve the hook
      • next(false): abort the current navigation
      • next(‘/‘) OR next({path:’/‘}): redirect. Can pass any location object (with replace, name, etc)
      • next(error): error will be passed to callbacks registered via router.onError()
  • only call next once
  • pre-route guard (beforeEnter): can be define in routes. Same signature as global
  • in-component guard: defined in route component
    • beforeRouteEnter: called before route entering this component is confirmed (thus no access to this but we can call next if we want to access the component instance)
    • beforeRouteUpdate: called before route changes. Doesn’t matter if component is reused or not unless provide a key to router-view
    • beforeRouteLeave: called before navigating away from route
    • can add via mixin but remember to declare after installing router plugin (Vue.use(Router))

Route Meta Fields

  • pass meta when defining routes
  • can be access on route location and navigation guards
  • each object in routes = route record
  • we can loop through route.matched to look for meta


  • <transition>
  • put one in each route component if want different transition for each
  • can also watch $route in parent to create route-based dynamic transition

Data Fetching

  • fetching before navigation
    • navigate and render the component immediately, fetch data in created hook.
    • can display loading screen
    • watch for update
  • fetching after navigation
    • fetch data before navigating to the new route, in beforeRouteEnter guard in the incoming component and call next when completed
    • beforeRouteUpdate for update
    • can display progress bar

Scroll Behaviour

  • pass scrollBehavior when defining routes
  • arguments: to, from, savedPosition (only avialable if triggered by the browser’s back/forward buttons <- “popstate” navigation)
  • scrollBehavior returns a scroll position object OR Promise
  • can smooth scrolling

Lazy Loading Routes

  • split each route’s components into a separate chunk, and only load them when the route is visited
  • = Vue’s async component feature + web pack’s code splitting feature
    • async component as factory function that returns Promise
    • use webpack’s dynamic import syntax to indicate a code-split point
  • can group components into the same async chunk by using named chunks
  • router-link will not log error for next(false), next(new Error()), and user already on the page, but router.push and router.replace would
  • Navigation Failures = Error instances + extra properties
  • use isNavigationFailure(failure, NavigationFailureType.n?) to check
    • n = redirected, aborted, cancelled, duplicated
    • failure has to and from, can check path on them