Alicante 29 May 2019
🌍 Vue core team
👨💻 Freelance
📍Paris
🐣 Málaga 🇪🇸
Routing in you App
the 1st week
Routing in your App
after a year
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>
router.push('/search')
<router-view/>
Store visited URLs
JS ↔ URL
push() replace(), ...
listen()
Route matching
match()
resolve()
Navigation
currentRoute
push() replace(), ...
beforeEach(), ...
Creating routes
new Router({ routes })
addRoutes()
<router-view/>
<router-link to="/">Home</router-link>
✍️ Imperative
✅ Programmatic navigation
❌ Declarative navigation
✅ Navigation Guards
❌ Dynamic routing (add/remove routes)
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>
✍️ Declarative
⚠️ Programmatic navigation (in-jsx)
✅ Declarative navigation
❌ Navigation Guards
✅ Dynamic routing (add/remove routes)
✍️ Configuration-based
✅ Programmatic navigation
✅ Declarative navigation
✅ Navigation Guards
⚠️ Dynamic routing (add/remove routes)
📦 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
this.$route
{
path: '/users/2',
name: 'UserProfile',
query: {},
params: { id: '2' },
meta: {}
}
<p>User: {{ $route.params.id }}</p>
created () {
fetch(`/api/users/${this.$route.params.id}`)
.then(/* ... */)
}
this.$route
created () {
if (someCondition) {
this.$router.push('/other-route')
}
}
this.$router
const router = new Router({
mode: 'history',
routes: [
{ path: '/', component: Home },
{ path: '/users/:id', component: UserProfile },
]
})
router.beforeEach((to, from, next) => {
// verify roles based on `to`
// ...
// we can only 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
await Admin()
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)
}
history.push
function push (location, onComplete, onAbort) {
const route = this.router.match(location, this.currentLocation)
try {
// run navigation guards queue
// ...
// change the url in the browser (HTML5)
window.history.pushState({}, '', route.fullPath)
onComplete(route)
} catch (error) {
// handle the error
// ...
onAbort(error)
}
}
⚠️ Simplified version
😨 Complex codebase
🙂 Simple codebase
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
Each segment gets 4 points and then…
Static segments get 3 more points
Dynamic segments 2 more
Root segments 1
and finally wildcard segments get a 1 point penalty
Navigation
currentRoute
push() replace()
Navigation Guards
beforeEach()
API
Responsibilities / Expectations
vue-router/push-state.js
reach-router/history.js
Directly navigate to
/é?é=é#é
location.pathname: '/%C3%A9'
location.search: '%C3%A9=%C3%A9'
location.search: '#%C3%A9'
location.pathname: '/é'
location.search: 'é=é'
location.search: '#é'
history.pushState({}, '', '/é?é=é#é')
export type RouteRecord =
| RouteRecordSingleView
| RouteRecordMultipleViews
| RouteRecordRedirect
Making sure we cover all cases from previous router
Router
prototype
other routers
other routers
Support both versions
Vue Router
Vue Router
Vue 2
Vue 3