London 4th Oct 2019
🌍 Vue core team
👨‍💻 Freelance
📍Paris
Routing in you App
the 1st week
Routing in your App
after a year
âś… Programmatic navigation
❌ Declarative navigation
âś… Navigation Guards
❌ Dynamic routing (add/remove routes)
❌ Declarative routing
router.addRoute('/some-route', options)
router.removeRoute('/some-route')⚠️ not actual API
<Router>
  <Home path="/" />
  <UserProfileEdit path="/users/:id/edit" />
</Router><div>
  <Link to="/">Home</Link>
  <Link to={`/users/${this.user.id}/edit`} />
</div>âś… Programmatic navigation
âś…Â Declarative navigation
❌ Navigation Guards
âś… Dynamic routing
âś…Â Declarative routing
Â
const router = new Router({
  mode: 'history',
  routes: [
    { path: '/', component: Home },
    { path: '/users/:id', component: UserProfile },
  ]
})<div>
  <router-link to="/">Home</router-link>
  <router-link :to="`/users/${this.user.id}`">
    My Profile
  </router-link>
</div>âś…Â Programmatic navigation
âś…Â Declarative navigation
âś… Navigation Guards
⚠️ Dynamic routing (add/remove routes)
❌ Declarative routing
<router-view/><router-link to="/">Home</router-link>Route matching​
​match()
​resolve()
Navigation
​​currentRoute
push() replace(), ...
​beforeEach(), ...
Creating routes
new Router({ routes })
		addRoutes()
JS ↔ URL
push() replace(), ...
listen()
📦 router-view
<router-view/>$route
📦 router-link
<router-link to="/">Home</router-link><router-link :to="{ name: 'User', params: {id: '2'}}">...</router-link>$route
$router
{
  path: '/users/2',
  fullPath: '/users/2?q=foo'
  name: 'UserProfile',
  query: { q: foo },
  hash: '',
  params: { id: '2' },
  meta: {}
}router.beforeEach((to, from, next) => {
  // verify roles based on `to`
  // ...
  // call `next` *once*
  if (!isLoggedIn) next('/login') // redirect to login
  else if (!isAuthorized) next(false) // abort
  else next() // allow navigation
}){
  path: '/admin',
  component: AdminPanel,
  beforeEnter (to, from, next) {
    if (isAdmin) next()
    else next(false)
  },
}export default {
  name: 'AdminPanel',
  data: () => ({ adminInfo: null }),
  async beforeRouteEnter (to, from, next) {
    const adminInfo = await getAdminInfo()
    next(vm => {
      vm.adminInfo = adminInfo
    })
  },
}beforeEach
beforeEnter
beforeRouteEnter
next()
next(false)
/posts ➡️ /admin
/posts
Admin.vue
beforeEnter
beforeRouteEnter
next()
/posts ➡️ /admin
Fetch Admin Component
History
Router
router.beforeEach
function beforeEach(guard: NavigationGuard): ListenerRemover {
  this.beforeGuards.push(guard)
  return () => {
    const i = this.beforeGuards.indexOf(guard)
    if (i > -1) this.beforeGuards.splice(i, 1)
  }
}router.push
function push (location, onComplete, onAbort) {
  this.history.push(location, onComplete, onAbort)
}beforeRouteEnter
<template>
  <p>Hello {{ user.name }}!</p>
</template>
<script>
  export default {
    data: () => ({ user: null }),
    async beforeRouteEnter(to, from, next) {
      const user = await fetchCurrentUser()
      next(vm => {
        vm.user = user
      })
    }
  }
</script>Oops!
After mounted
beforeRouteEnter
beforeRouteUpdate beforeRouteLeave
❌ No access to the component instance (this)
âś… Can pass a callback
âś… Access to the component instance (this)
❌ Callback is ignored
Store visited URLs
JS ↔ URL
push() replace(), ...
listen()
Route matching
​match()
​resolve()
Navigation
​​currentRoute
push() replace(), ...
​beforeEach(), ...
Creating routes
new Router({ routes })
		addRoutes()
push() replace()
listen()
API
Responsibilities / Expectations
Route matching
​resolve()
addRouteRecord
removeRouteRecord
Navigation
​​currentRoute
push() replace(), ...
Navigation Guards
​beforeEach(), ...
​addRoute / removeRoute
Route matching
​resolve()
addRouteRecord
removeRouteRecord
API
Responsibilities / Expectations
Navigation
​​currentRoute
push(), replace()
Navigation Guards
​beforeEach(), ...
API
Responsibilities / Expectations
export type RouteRecord =
  | RouteRecordSingleView
  | RouteRecordMultipleViews
  | RouteRecordRedirect<router-link
  to="/about"
  v-slot="{ href, route, navigate, isActive }"
>
  <NavLink
    :active="isActive"
    :href="href"
    @click="navigate"
  >{{ route.fullPath }}</NavLink>
</router-link>try {
  await router.push('/somewhere')
} catch (err) {
  console.log(
    'Did not make it to ' + err.to.fullPath
  )
}function createHistory(): RouterHistory {
  const base = createAbstractHistory()
  const navigationStack = []
  
  // overload push/replace methods to write the stack
  function push() {}
  function replace() {}
  
  return {
    ...base,
    
    push,
    replace,
    navigationStack,
  }
}new Router({
  mode: createHistory(),
})new Router({
  routes: [
    { path: '/(.*)', name: 'NotFound' },
    { path: '/home', name: 'Home' }
  ]
})paths.esm.dev
router.addRoute({ name: 'User', path: '/users/:id' })
router.addRoute({ name: 'UserById', path: '/users/:id(\d+)' })
router.addRoute({ name: 'Myself', path: '/users/me' })
router.removeRoute({ name: 'TemporaryRoute' })
router.resolve('/users/me') // -> { name: 'Myself' }
router.resolve('/users/230') // -> { name: 'UserById' }
router.resolve('/users/posva') // -> { name: 'User' }secret
routes
if (loggedIn) router.addRoutes()
import { useLink } from 'vue-router'
function useConfirmLink(to, message) {
  const link = useLink(to)
  
  function navigate() {
    if (window.confirm(message)) return link.navigate()
  }
  
  return { ...link, navigate }
}​useLink
useLocation
onBeforeRouteLeave
onBeforeRouteUpdate
Vue Router
Vue Router
Vue 2
Vue 3