SlideShare a Scribd company logo
How to Build SPA with Vue
Router 2.0
2016/08/24
Takuya Tejima
Who?
• Takuya Tejima @tejitak
• Co-Founder & CTO at Indie Inc. (ex-IBM, ex-LINE)
• Server & Web Front-End & iOS Engineer
• Community
• Vue.js core team member
• Dev Morning community founder
• http://devmorning.connpass.com/
• Global Startup Creators co-founder
• https://www.facebook.com/globalstartupcreators/
What’s SPA
• SPA (Single Page Aplication)
• SPA is a web application or web site that fits on a single web page with the goal of providing a more fluid user
experience similar to a desktop application.
• Important things to introduce
• Does you app really need to be SPA, such as partial rendering?
• It may not be easy compare to typical standard server side implementation
• There are no best frameworks for all situations
• There are a lot of frameworks
• Backbone? Ember? Riot? Angular + ui-router? Angular 2? React + React-Router (+ Redux)? Vue.js + Vue-
Router (+ Vuex)?
• If you decide to build SPA on your next webapp project, Vue.js + Vue Router would be a good option
• Vue Router Features
• Dead simple for component mapping with routes
• Nested routes and sub components
• Support SSR (Server Side Rendering) and Virtual DOM
• Async load
• Flexible hooks
• History management, Scroll behavior, transition etc.
• Vue Router 2.0 (Currently Beta) is really powerful!! Especially on…
• Better performance for SPA by reactive components mechanism
• SSR & SPA with isomorphic fetch and client hydration
• It means the components will dynamically work in client side generated by server side
same modules. It’s available without server side template engine like EJS! And, it has
better SEO compared to ordinary SPA
What’s Vue Router?
Work with SSR
• What’s BundleRenderer?
• Generate components for each requests from code to prevent shared modules on node
• TIPS: To skip parsing entire app dependencies every requests, we can specify webpack externals
options
Cont. Work with SSR
import Vue from 'vue'
import App from './App.vue'
import store from './store'
import router from './router'
import { sync } from 'vuex-router-sync'
// sync the router with the vuex store.
// this registers `store.state.route`
sync(store, router)
const app = new Vue({
router,
store,
...App
})
export { app, router, store }
app.js
require('es6-promise').polyfill()
import { app, store } from './app'
store.replaceState(window.__INITIAL_STATE__)
app.$mount('#app')
client-entry.js
import { app, router, store } from './app'
const isDev = process.env.NODE_ENV !== 'production'
export default context => {
router.push(context.url)
const s = isDev && Date.now()
return
Promise.all(router.getMatchedComponents().map(component => {
if (component.preFetch) {
return component.preFetch(store)
}
})).then(() => {
context.initialState = store.state
return app
})
}
server-entry.js
Client Side Hydration
• Client side Vue instance will attempt to "hydrate" the existing DOM instead of creating
new DOM nodes when the server-rendered="true" attribute exists
• Demo: Vue hackernews 2.0
• https://github.com/vuejs/vue-hackernews-2.0
• SSR + SPA (Client side hydration) can be achieved by Vue 2.0 & Vue Router
2.0 & Vuex 2.0!
• Vue: SSR
• Vue Router: Routing mapping management
• Vuex: State management & Isomorphic data fetch
Isomorphic Data Fetch with Vuex
import Vue from 'vue'
import Vuex from 'vuex'
import {fetchItems} from './api'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
itemsPerPage: 20,
items: {/* [id: number]: Item */}
},
actions: {
FETCH_ITEMS: ({ commit, state }, { ids }) => {
ids = ids.filter(id => !state.items[id])
if (ids.length) {
return fetchItems(ids).then(items =>
commit('SET_ITEMS', { items }))
} else {
return Promise.resolve()
}
}
},
mutations: {
SET_ITEMS: (state, { items }) => {
items.forEach(item => {
if (item) {
Vue.set(state.items, item.id, item)
}
})
}
}
})
export default store
store/index.js store/api.js
import Firebase from 'firebase'
const api = new Firebase('https://hacker-
news.firebaseio.com/v0')
function fetch (child) {
return new Promise((resolve, reject) => {
api.child(child).once('value', snapshot => {
resolve(snapshot.val())
}, reject)
})
}
export function fetchItem (id) {
return fetch(`item/${id}`)
}
export function fetchItems (ids) {
return Promise.all(ids.map(id =>
fetchItem(id)))
}
Server Side Component Cache
• Server side cache makes SSR +
SPA faster
• Component layer server side cache
• cache components by implementing
the serverCacheKey function
• API layer server side cache
• LRU cache examples:
const cache = inBrowser
? null
: (process.__API_CACHE__ || (process.__API_CACHE__ =
createCache()))
function createCache () {
return LRU({
max: 1000,
maxAge: 1000 * 60 * 15 // 15 min cache
})
}
const api = inBrowser
? new Firebase('https://hacker-news.firebaseio.com/v0')
: (process.__API__ || (process.__API__ =
createServerSideAPI()))
export default {
name: 'item', // required
props: ['item'],
serverCacheKey: props => props.item.id,
render (h) {
return h('div', this.item.id)
}
}
• Picked breaking changes from previous version
• Install
• routes config are changed to Array
• Navigations
• history.go -> history.push
• v-link directive -> <router-link> component
• Hooks
• The hooks data, activate, deactivate, canActivate, canDeactivate, canReuse are now replaced
• activate & deactivate -> Component's own lifecycle hooks
• data -> Use a watcher on $route to react to route changes
• canActivate -> beforeEnter guards declared in route configurations
• canDeactivate -> beforeRouteLeave defined at the root level of a component's definition
• canReuse -> removed because it is confusing and rarely useful
Migration from Vue Router v0.x.x
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/users', component: Users,
children: [
{ path: ':username', component: User }
]
}
]
})
watch: {
'$route': 'fetchData'
}
1. Use plugin
2. Define route components
3. Create the router
4. Create and mount root instance.
Vue Router 2.0 - Install
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{ path: '/', component: { template: '<div>home</div>' } },
{ path: '/foo', component: { template: '<div>foo</div>' } },
{ path: '/bar', component: { template: '<div>bar</div>' } }
]
})
new Vue({
router,
template: `
<div id="app">
<ul>
<li><router-link to="/">/</router-link></li>
<li><router-link to="/foo">/foo</router-link></li>
<li><router-link to="/bar">/bar</router-link></li>
</ul>
<router-view class="view"></router-view>
</div>
`
}).$mount('#app')
• Examples
Vue Router 2.0 - <router-link>
<li><router-link to="/">/</router-link></li>
<li><router-link to="/users" exact>/users (exact match)</router-link></li>
<li><router-link to="/users/evan#foo">/users/evan#foo</router-link></li>
<li>
<router-link :to="{ path: '/users/evan', query: { foo: 'bar', baz: 'qux' }}">
/users/evan?foo=bar&baz=qux
</router-link>
</li>
• A single route can define multiple named components
Vue Router 2.0 - Named view
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{ path: '/',
components: {
default: Foo,
a: Bar,
b: Baz
}
},
{
path: '/other',
components: {
default: Baz,
a: Bar,
b: Foo
}
}
]
})
new Vue({
router,
data () {
return {
name: 'b'
}
},
watch: {
'$route' () {
this.name = 'a'
}
},
template: `
<div id="app">
<h1>Named Views</h1>
<ul>
<li><router-link to="/">/</router-link></li>
<li><router-link to="/other">/other</router-link></li>
</ul>
<router-view class="view one"></router-view>
<router-view class="view two" :name="name"></router-view>
<router-view class="view three" name="b"></router-view>
</div>
`
}).$mount('#app')
router config vue instance
• Alias / Redirect examples
Vue Router 2.0 - Alias / Redirect
routes: [
{ path: '/home', component: Home,
children: [
// absolute alias
{ path: 'foo', component: Foo, alias: '/foo' },
// relative alias (alias to /home/bar-alias)
{ path: 'bar', component: Bar, alias: 'bar-alias' },
// multiple aliases
{ path: 'baz', component: Baz, alias: ['/baz', 'baz-alias'] }
]
},
// absolute redirect
{ path: '/absolute-redirect', redirect: '/bar' },
// named redirect
{ path: '/named-redirect', redirect: { name: 'baz' }},
// redirect with params
{ path: '/redirect-with-params/:id', redirect: '/with-params/:id' },
// catch all redirect
{ path: '*', redirect: '/' }
]
• beforeEnter examples
Vue Router 2.0 - Guard Examples 1
import Dashboard from './components/Dashboard.vue'
import Login from './components/Login.vue'
function requireAuth (route, redirect, next) {
if (!auth.loggedIn()) {
redirect({
path: '/login',
query: { redirect: route.fullPath }
})
} else {
next()
}
}
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{ path: '/dashboard', component: Dashboard, beforeEnter: requireAuth },
{ path: '/login', component: Login }
]
})
https://github.com/vuejs/vue-router/blob/next/examples/auth-flow/app.js
• beforeRouterLeave examples
Vue Router 2.0 - Guard Examples 2
const Baz = {
data () {
return { saved: false }
},
template: `
<div>
<p>baz ({{ saved ? 'saved' : 'not saved' }})<p>
<button @click="saved = true">save</button>
</div>
`,
beforeRouteLeave (route, redirect, next) {
if (this.saved || window.confirm('Not saved, are you sure you want to navigate away?')) {
next()
}
}
}
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{ path: '/', component: Home },
{ path: '/baz', component: Baz }
]
})
https://github.com/vuejs/vue-router/blob/next/examples/navigation-guards/app.js
• Webpack will automatically split and lazy-load the split modules
when using AMD require syntax
Vue Router 2.0 - Async Components
const Foo = resolve => require(['./Foo.vue'], resolve)
const Bar = resolve => require(['./Bar.vue'], resolve)
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{ path: '/', component: Home },
// Just use them normally in the route config
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
})
https://github.com/vuejs/vue-router/blob/next/examples/lazy-loading/app.js
• scrollBehavior
• only available in html5 history mode
• defaults to no scroll behavior
• return false to prevent scroll
Vue Router 2.0 - scrollBehavior
const scrollBehavior = (to, from, savedPosition) => {
if (savedPosition) {
return savedPosition
} else {
const position = {}
// new navigation.
// scroll to anchor by returning the selector
if (to.hash) {
position.selector = to.hash
}
if (to.matched.some(m => m.meta.scrollToTop)) {
// cords will be used if no selector is provided,
// or if the selector didn't match any element.
position.x = 0
position.y = 0
}
// if the returned position is falsy or an empty object,
// will retain current scroll position.
return position
}
}
const router = new VueRouter({
mode: 'history',
base: __dirname,
scrollBehavior,
routes: [
{ path: '/', component: Home, meta: { scrollToTop: true }},
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar, meta: { scrollToTop: true }}
]
})
https://github.com/vuejs/vue-router/blob/next/examples/scroll-behavior/app.js
• Transition
• Dynamically transition setting on route change are available
Vue Router 2.0 - Transition
const Parent = {
data () {
return {
transitionName: 'slide-left'
}
},
// dynamically set transition based on route change
watch: {
'$route' (to, from) {
const toDepth = to.path.split('/').length
const fromDepth = from.path.split('/').length
this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
}
},
template: `
<div class="parent">
<h2>Parent</h2>
<transition :name="transitionName">
<router-view class="child-view"></router-view>
</transition>
</div>
`
}
https://github.com/vuejs/vue-router/blob/next/examples/transitions/app.js
• Vue Router x Vuex
• Inject (sync) router states to Vuex states
• Components can access router data (path, params, query)
through vuex getter in components router
• https://github.com/vuejs/vuex-router-sync
Vue Router 2.0 - Vuex Router Sync
SPA with Awesome Vue Family
• Building SPA with Vue.js 2.0 Family
• Better performance for SPA by reactive components mechanism
• SSR & SPA with isomorphic fetch and client hydration
• No worried about SEO & server side template like EJS
• Seamless integration with Vue-Router & Vuex modules compare to
React & React-Router & Redux because the author is same Evan :)
It allows us more consistent & intuitive coding manner
Thanks!
Join Slack (Japanese)
https://vuejs-jp-slackin.herokuapp.com/

More Related Content

What's hot

Vue js 大型專案架構
Vue js 大型專案架構Vue js 大型專案架構
Vue js 大型專案架構
Hina Chen
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
Tudor Barbu
 
Vue 淺談前端建置工具
Vue 淺談前端建置工具Vue 淺談前端建置工具
Vue 淺談前端建置工具
andyyou
 
Vue 2.0 + Vuex Router & Vuex at Vue.js
Vue 2.0 + Vuex Router & Vuex at Vue.jsVue 2.0 + Vuex Router & Vuex at Vue.js
Vue 2.0 + Vuex Router & Vuex at Vue.js
Takuya Tejima
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todaygerbille
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JS
Eueung Mulyana
 
Vue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue routerVue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue router
Katy Slemon
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widget
Tudor Barbu
 
Vue js and Vue Material
Vue js and Vue MaterialVue js and Vue Material
Vue js and Vue Material
Eueung Mulyana
 
以Vue開發電子商務網站
架構與眉角
以Vue開發電子商務網站
架構與眉角以Vue開發電子商務網站
架構與眉角
以Vue開發電子商務網站
架構與眉角
Mei-yu Chen
 
第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]
Kuro Hsu
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
David Ličen
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & Vuex
Bernd Alter
 
Why Vue.js?
Why Vue.js?Why Vue.js?
Why Vue.js?
Jonathan Goode
 
Scalable Front-end Development with Vue.JS
Scalable Front-end Development with Vue.JSScalable Front-end Development with Vue.JS
Scalable Front-end Development with Vue.JS
Galih Pratama
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting Started
Murat Doğan
 
Room with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.jsRoom with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.js
Zachary Klein
 
Vuejs for Angular developers
Vuejs for Angular developersVuejs for Angular developers
Vuejs for Angular developers
Mikhail Kuznetcov
 
Famo.us - New generation of HTML5 Web Application Framework
Famo.us - New generation of HTML5 Web Application FrameworkFamo.us - New generation of HTML5 Web Application Framework
Famo.us - New generation of HTML5 Web Application Framework
Hina Chen
 
Vue.js for beginners
Vue.js for beginnersVue.js for beginners
Vue.js for beginners
Julio Bitencourt
 

What's hot (20)

Vue js 大型專案架構
Vue js 大型專案架構Vue js 大型專案架構
Vue js 大型專案架構
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
 
Vue 淺談前端建置工具
Vue 淺談前端建置工具Vue 淺談前端建置工具
Vue 淺談前端建置工具
 
Vue 2.0 + Vuex Router & Vuex at Vue.js
Vue 2.0 + Vuex Router & Vuex at Vue.jsVue 2.0 + Vuex Router & Vuex at Vue.js
Vue 2.0 + Vuex Router & Vuex at Vue.js
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of today
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JS
 
Vue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue routerVue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue router
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widget
 
Vue js and Vue Material
Vue js and Vue MaterialVue js and Vue Material
Vue js and Vue Material
 
以Vue開發電子商務網站
架構與眉角
以Vue開發電子商務網站
架構與眉角以Vue開發電子商務網站
架構與眉角
以Vue開發電子商務網站
架構與眉角
 
第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & Vuex
 
Why Vue.js?
Why Vue.js?Why Vue.js?
Why Vue.js?
 
Scalable Front-end Development with Vue.JS
Scalable Front-end Development with Vue.JSScalable Front-end Development with Vue.JS
Scalable Front-end Development with Vue.JS
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting Started
 
Room with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.jsRoom with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.js
 
Vuejs for Angular developers
Vuejs for Angular developersVuejs for Angular developers
Vuejs for Angular developers
 
Famo.us - New generation of HTML5 Web Application Framework
Famo.us - New generation of HTML5 Web Application FrameworkFamo.us - New generation of HTML5 Web Application Framework
Famo.us - New generation of HTML5 Web Application Framework
 
Vue.js for beginners
Vue.js for beginnersVue.js for beginners
Vue.js for beginners
 

Similar to How to Build SPA with Vue Router 2.0

How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
Love at first Vue
Love at first VueLove at first Vue
Love at first Vue
Dalibor Gogic
 
Vue js and Dyploma
Vue js and DyplomaVue js and Dyploma
Vue js and Dyploma
Yoram Kornatzky
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
Ben Lin
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
Javier Abadía
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applications
Astrails
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Frost
 
Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017
Elyse Kolker Gordon
 
Modern JavaScript, without giving up on Rails
Modern JavaScript, without giving up on RailsModern JavaScript, without giving up on Rails
Modern JavaScript, without giving up on Rails
Jonathan Johnson
 
A re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiA re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbai
Praveen Puglia
 
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Codemotion
 
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Luciano Mammino
 
Aurelia Meetup Paris
Aurelia Meetup ParisAurelia Meetup Paris
Aurelia Meetup Paris
Ahmed Radjdi
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
Pagepro
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
Sapna Upreti
 
How to implement multiple layouts using React router V4.pptx
How to implement multiple layouts using React router V4.pptxHow to implement multiple layouts using React router V4.pptx
How to implement multiple layouts using React router V4.pptx
BOSC Tech Labs
 
Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics
Eliran Eliassy
 
State manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to VuexState manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to Vuex
Commit University
 
Introducing Vuex in your project
Introducing Vuex in your projectIntroducing Vuex in your project
Introducing Vuex in your project
Denny Biasiolli
 
Voorhoede - Front-end architecture
Voorhoede - Front-end architectureVoorhoede - Front-end architecture
Voorhoede - Front-end architecture
Jasper Moelker
 

Similar to How to Build SPA with Vue Router 2.0 (20)

How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
Love at first Vue
Love at first VueLove at first Vue
Love at first Vue
 
Vue js and Dyploma
Vue js and DyplomaVue js and Dyploma
Vue js and Dyploma
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applications
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
 
Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017
 
Modern JavaScript, without giving up on Rails
Modern JavaScript, without giving up on RailsModern JavaScript, without giving up on Rails
Modern JavaScript, without giving up on Rails
 
A re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiA re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbai
 
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
 
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
 
Aurelia Meetup Paris
Aurelia Meetup ParisAurelia Meetup Paris
Aurelia Meetup Paris
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 
How to implement multiple layouts using React router V4.pptx
How to implement multiple layouts using React router V4.pptxHow to implement multiple layouts using React router V4.pptx
How to implement multiple layouts using React router V4.pptx
 
Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics
 
State manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to VuexState manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to Vuex
 
Introducing Vuex in your project
Introducing Vuex in your projectIntroducing Vuex in your project
Introducing Vuex in your project
 
Voorhoede - Front-end architecture
Voorhoede - Front-end architectureVoorhoede - Front-end architecture
Voorhoede - Front-end architecture
 

More from Takuya Tejima

Nest.js Introduction
Nest.js IntroductionNest.js Introduction
Nest.js Introduction
Takuya Tejima
 
モダンフロントエンド開発者に求められるスキルとは
モダンフロントエンド開発者に求められるスキルとはモダンフロントエンド開発者に求められるスキルとは
モダンフロントエンド開発者に求められるスキルとは
Takuya Tejima
 
Next.js Storybook Driven Development
Next.js Storybook Driven DevelopmentNext.js Storybook Driven Development
Next.js Storybook Driven Development
Takuya Tejima
 
グローバルエンジニアキャリア はじめの一歩
グローバルエンジニアキャリア はじめの一歩グローバルエンジニアキャリア はじめの一歩
グローバルエンジニアキャリア はじめの一歩
Takuya Tejima
 
GAOGAO発表資料〜エンジニアギルドミートアップ〜
GAOGAO発表資料〜エンジニアギルドミートアップ〜GAOGAO発表資料〜エンジニアギルドミートアップ〜
GAOGAO発表資料〜エンジニアギルドミートアップ〜
Takuya Tejima
 
Laravel管理画面ジェネレーター
Laravel管理画面ジェネレーターLaravel管理画面ジェネレーター
Laravel管理画面ジェネレーター
Takuya Tejima
 
エンジニア・コミュニティ・ドリブンで会社を成長させていくGAOGAO
エンジニア・コミュニティ・ドリブンで会社を成長させていくGAOGAOエンジニア・コミュニティ・ドリブンで会社を成長させていくGAOGAO
エンジニア・コミュニティ・ドリブンで会社を成長させていくGAOGAO
Takuya Tejima
 
「コリビング&コワーキング / スキルアップ / ジョブマッチング / 起業支援」GAOGAO(ガオガオ)エンジニア事務所 18
 「コリビング&コワーキング / スキルアップ / ジョブマッチング / 起業支援」GAOGAO(ガオガオ)エンジニア事務所 18  「コリビング&コワーキング / スキルアップ / ジョブマッチング / 起業支援」GAOGAO(ガオガオ)エンジニア事務所 18
「コリビング&コワーキング / スキルアップ / ジョブマッチング / 起業支援」GAOGAO(ガオガオ)エンジニア事務所 18
Takuya Tejima
 
GAOGAO (ガオガオ) サービス事業概要 2018年8月
GAOGAO (ガオガオ) サービス事業概要 2018年8月GAOGAO (ガオガオ) サービス事業概要 2018年8月
GAOGAO (ガオガオ) サービス事業概要 2018年8月
Takuya Tejima
 
GAOGAOゲート2期生サービス概要資料
GAOGAOゲート2期生サービス概要資料GAOGAOゲート2期生サービス概要資料
GAOGAOゲート2期生サービス概要資料
Takuya Tejima
 
GAOGAO事業のご紹介
GAOGAO事業のご紹介GAOGAO事業のご紹介
GAOGAO事業のご紹介
Takuya Tejima
 
Global Creators Workshop in Asia
Global Creators Workshop in AsiaGlobal Creators Workshop in Asia
Global Creators Workshop in Asia
Takuya Tejima
 
Global Startup Creators vol.5 - Facebook bot development handson
Global Startup Creators vol.5 - Facebook bot development handsonGlobal Startup Creators vol.5 - Facebook bot development handson
Global Startup Creators vol.5 - Facebook bot development handson
Takuya Tejima
 
Parseでちゃんとアプリを作るコツ
Parseでちゃんとアプリを作るコツParseでちゃんとアプリを作るコツ
Parseでちゃんとアプリを作るコツ
Takuya Tejima
 
DevMorning
DevMorningDevMorning
DevMorning
Takuya Tejima
 
React Canvasで作るFlappy Bird
React Canvasで作るFlappy BirdReact Canvasで作るFlappy Bird
React Canvasで作るFlappy Bird
Takuya Tejima
 

More from Takuya Tejima (16)

Nest.js Introduction
Nest.js IntroductionNest.js Introduction
Nest.js Introduction
 
モダンフロントエンド開発者に求められるスキルとは
モダンフロントエンド開発者に求められるスキルとはモダンフロントエンド開発者に求められるスキルとは
モダンフロントエンド開発者に求められるスキルとは
 
Next.js Storybook Driven Development
Next.js Storybook Driven DevelopmentNext.js Storybook Driven Development
Next.js Storybook Driven Development
 
グローバルエンジニアキャリア はじめの一歩
グローバルエンジニアキャリア はじめの一歩グローバルエンジニアキャリア はじめの一歩
グローバルエンジニアキャリア はじめの一歩
 
GAOGAO発表資料〜エンジニアギルドミートアップ〜
GAOGAO発表資料〜エンジニアギルドミートアップ〜GAOGAO発表資料〜エンジニアギルドミートアップ〜
GAOGAO発表資料〜エンジニアギルドミートアップ〜
 
Laravel管理画面ジェネレーター
Laravel管理画面ジェネレーターLaravel管理画面ジェネレーター
Laravel管理画面ジェネレーター
 
エンジニア・コミュニティ・ドリブンで会社を成長させていくGAOGAO
エンジニア・コミュニティ・ドリブンで会社を成長させていくGAOGAOエンジニア・コミュニティ・ドリブンで会社を成長させていくGAOGAO
エンジニア・コミュニティ・ドリブンで会社を成長させていくGAOGAO
 
「コリビング&コワーキング / スキルアップ / ジョブマッチング / 起業支援」GAOGAO(ガオガオ)エンジニア事務所 18
 「コリビング&コワーキング / スキルアップ / ジョブマッチング / 起業支援」GAOGAO(ガオガオ)エンジニア事務所 18  「コリビング&コワーキング / スキルアップ / ジョブマッチング / 起業支援」GAOGAO(ガオガオ)エンジニア事務所 18
「コリビング&コワーキング / スキルアップ / ジョブマッチング / 起業支援」GAOGAO(ガオガオ)エンジニア事務所 18
 
GAOGAO (ガオガオ) サービス事業概要 2018年8月
GAOGAO (ガオガオ) サービス事業概要 2018年8月GAOGAO (ガオガオ) サービス事業概要 2018年8月
GAOGAO (ガオガオ) サービス事業概要 2018年8月
 
GAOGAOゲート2期生サービス概要資料
GAOGAOゲート2期生サービス概要資料GAOGAOゲート2期生サービス概要資料
GAOGAOゲート2期生サービス概要資料
 
GAOGAO事業のご紹介
GAOGAO事業のご紹介GAOGAO事業のご紹介
GAOGAO事業のご紹介
 
Global Creators Workshop in Asia
Global Creators Workshop in AsiaGlobal Creators Workshop in Asia
Global Creators Workshop in Asia
 
Global Startup Creators vol.5 - Facebook bot development handson
Global Startup Creators vol.5 - Facebook bot development handsonGlobal Startup Creators vol.5 - Facebook bot development handson
Global Startup Creators vol.5 - Facebook bot development handson
 
Parseでちゃんとアプリを作るコツ
Parseでちゃんとアプリを作るコツParseでちゃんとアプリを作るコツ
Parseでちゃんとアプリを作るコツ
 
DevMorning
DevMorningDevMorning
DevMorning
 
React Canvasで作るFlappy Bird
React Canvasで作るFlappy BirdReact Canvasで作るFlappy Bird
React Canvasで作るFlappy Bird
 

Recently uploaded

HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
ShahidSultan24
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Kamal Acharya
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 

Recently uploaded (20)

HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 

How to Build SPA with Vue Router 2.0

  • 1. How to Build SPA with Vue Router 2.0 2016/08/24 Takuya Tejima
  • 2. Who? • Takuya Tejima @tejitak • Co-Founder & CTO at Indie Inc. (ex-IBM, ex-LINE) • Server & Web Front-End & iOS Engineer • Community • Vue.js core team member • Dev Morning community founder • http://devmorning.connpass.com/ • Global Startup Creators co-founder • https://www.facebook.com/globalstartupcreators/
  • 3. What’s SPA • SPA (Single Page Aplication) • SPA is a web application or web site that fits on a single web page with the goal of providing a more fluid user experience similar to a desktop application. • Important things to introduce • Does you app really need to be SPA, such as partial rendering? • It may not be easy compare to typical standard server side implementation • There are no best frameworks for all situations • There are a lot of frameworks • Backbone? Ember? Riot? Angular + ui-router? Angular 2? React + React-Router (+ Redux)? Vue.js + Vue- Router (+ Vuex)? • If you decide to build SPA on your next webapp project, Vue.js + Vue Router would be a good option
  • 4. • Vue Router Features • Dead simple for component mapping with routes • Nested routes and sub components • Support SSR (Server Side Rendering) and Virtual DOM • Async load • Flexible hooks • History management, Scroll behavior, transition etc. • Vue Router 2.0 (Currently Beta) is really powerful!! Especially on… • Better performance for SPA by reactive components mechanism • SSR & SPA with isomorphic fetch and client hydration • It means the components will dynamically work in client side generated by server side same modules. It’s available without server side template engine like EJS! And, it has better SEO compared to ordinary SPA What’s Vue Router?
  • 5. Work with SSR • What’s BundleRenderer? • Generate components for each requests from code to prevent shared modules on node • TIPS: To skip parsing entire app dependencies every requests, we can specify webpack externals options
  • 6. Cont. Work with SSR import Vue from 'vue' import App from './App.vue' import store from './store' import router from './router' import { sync } from 'vuex-router-sync' // sync the router with the vuex store. // this registers `store.state.route` sync(store, router) const app = new Vue({ router, store, ...App }) export { app, router, store } app.js require('es6-promise').polyfill() import { app, store } from './app' store.replaceState(window.__INITIAL_STATE__) app.$mount('#app') client-entry.js import { app, router, store } from './app' const isDev = process.env.NODE_ENV !== 'production' export default context => { router.push(context.url) const s = isDev && Date.now() return Promise.all(router.getMatchedComponents().map(component => { if (component.preFetch) { return component.preFetch(store) } })).then(() => { context.initialState = store.state return app }) } server-entry.js
  • 7. Client Side Hydration • Client side Vue instance will attempt to "hydrate" the existing DOM instead of creating new DOM nodes when the server-rendered="true" attribute exists • Demo: Vue hackernews 2.0 • https://github.com/vuejs/vue-hackernews-2.0 • SSR + SPA (Client side hydration) can be achieved by Vue 2.0 & Vue Router 2.0 & Vuex 2.0! • Vue: SSR • Vue Router: Routing mapping management • Vuex: State management & Isomorphic data fetch
  • 8. Isomorphic Data Fetch with Vuex import Vue from 'vue' import Vuex from 'vuex' import {fetchItems} from './api' Vue.use(Vuex) const store = new Vuex.Store({ state: { itemsPerPage: 20, items: {/* [id: number]: Item */} }, actions: { FETCH_ITEMS: ({ commit, state }, { ids }) => { ids = ids.filter(id => !state.items[id]) if (ids.length) { return fetchItems(ids).then(items => commit('SET_ITEMS', { items })) } else { return Promise.resolve() } } }, mutations: { SET_ITEMS: (state, { items }) => { items.forEach(item => { if (item) { Vue.set(state.items, item.id, item) } }) } } }) export default store store/index.js store/api.js import Firebase from 'firebase' const api = new Firebase('https://hacker- news.firebaseio.com/v0') function fetch (child) { return new Promise((resolve, reject) => { api.child(child).once('value', snapshot => { resolve(snapshot.val()) }, reject) }) } export function fetchItem (id) { return fetch(`item/${id}`) } export function fetchItems (ids) { return Promise.all(ids.map(id => fetchItem(id))) }
  • 9. Server Side Component Cache • Server side cache makes SSR + SPA faster • Component layer server side cache • cache components by implementing the serverCacheKey function • API layer server side cache • LRU cache examples: const cache = inBrowser ? null : (process.__API_CACHE__ || (process.__API_CACHE__ = createCache())) function createCache () { return LRU({ max: 1000, maxAge: 1000 * 60 * 15 // 15 min cache }) } const api = inBrowser ? new Firebase('https://hacker-news.firebaseio.com/v0') : (process.__API__ || (process.__API__ = createServerSideAPI())) export default { name: 'item', // required props: ['item'], serverCacheKey: props => props.item.id, render (h) { return h('div', this.item.id) } }
  • 10. • Picked breaking changes from previous version • Install • routes config are changed to Array • Navigations • history.go -> history.push • v-link directive -> <router-link> component • Hooks • The hooks data, activate, deactivate, canActivate, canDeactivate, canReuse are now replaced • activate & deactivate -> Component's own lifecycle hooks • data -> Use a watcher on $route to react to route changes • canActivate -> beforeEnter guards declared in route configurations • canDeactivate -> beforeRouteLeave defined at the root level of a component's definition • canReuse -> removed because it is confusing and rarely useful Migration from Vue Router v0.x.x const router = new VueRouter({ mode: 'history', base: __dirname, routes: [ { path: '/', component: Home }, { path: '/about', component: About }, { path: '/users', component: Users, children: [ { path: ':username', component: User } ] } ] }) watch: { '$route': 'fetchData' }
  • 11. 1. Use plugin 2. Define route components 3. Create the router 4. Create and mount root instance. Vue Router 2.0 - Install import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const router = new VueRouter({ mode: 'history', base: __dirname, routes: [ { path: '/', component: { template: '<div>home</div>' } }, { path: '/foo', component: { template: '<div>foo</div>' } }, { path: '/bar', component: { template: '<div>bar</div>' } } ] }) new Vue({ router, template: ` <div id="app"> <ul> <li><router-link to="/">/</router-link></li> <li><router-link to="/foo">/foo</router-link></li> <li><router-link to="/bar">/bar</router-link></li> </ul> <router-view class="view"></router-view> </div> ` }).$mount('#app')
  • 12. • Examples Vue Router 2.0 - <router-link> <li><router-link to="/">/</router-link></li> <li><router-link to="/users" exact>/users (exact match)</router-link></li> <li><router-link to="/users/evan#foo">/users/evan#foo</router-link></li> <li> <router-link :to="{ path: '/users/evan', query: { foo: 'bar', baz: 'qux' }}"> /users/evan?foo=bar&baz=qux </router-link> </li>
  • 13. • A single route can define multiple named components Vue Router 2.0 - Named view const router = new VueRouter({ mode: 'history', base: __dirname, routes: [ { path: '/', components: { default: Foo, a: Bar, b: Baz } }, { path: '/other', components: { default: Baz, a: Bar, b: Foo } } ] }) new Vue({ router, data () { return { name: 'b' } }, watch: { '$route' () { this.name = 'a' } }, template: ` <div id="app"> <h1>Named Views</h1> <ul> <li><router-link to="/">/</router-link></li> <li><router-link to="/other">/other</router-link></li> </ul> <router-view class="view one"></router-view> <router-view class="view two" :name="name"></router-view> <router-view class="view three" name="b"></router-view> </div> ` }).$mount('#app') router config vue instance
  • 14. • Alias / Redirect examples Vue Router 2.0 - Alias / Redirect routes: [ { path: '/home', component: Home, children: [ // absolute alias { path: 'foo', component: Foo, alias: '/foo' }, // relative alias (alias to /home/bar-alias) { path: 'bar', component: Bar, alias: 'bar-alias' }, // multiple aliases { path: 'baz', component: Baz, alias: ['/baz', 'baz-alias'] } ] }, // absolute redirect { path: '/absolute-redirect', redirect: '/bar' }, // named redirect { path: '/named-redirect', redirect: { name: 'baz' }}, // redirect with params { path: '/redirect-with-params/:id', redirect: '/with-params/:id' }, // catch all redirect { path: '*', redirect: '/' } ]
  • 15. • beforeEnter examples Vue Router 2.0 - Guard Examples 1 import Dashboard from './components/Dashboard.vue' import Login from './components/Login.vue' function requireAuth (route, redirect, next) { if (!auth.loggedIn()) { redirect({ path: '/login', query: { redirect: route.fullPath } }) } else { next() } } const router = new VueRouter({ mode: 'history', base: __dirname, routes: [ { path: '/dashboard', component: Dashboard, beforeEnter: requireAuth }, { path: '/login', component: Login } ] }) https://github.com/vuejs/vue-router/blob/next/examples/auth-flow/app.js
  • 16. • beforeRouterLeave examples Vue Router 2.0 - Guard Examples 2 const Baz = { data () { return { saved: false } }, template: ` <div> <p>baz ({{ saved ? 'saved' : 'not saved' }})<p> <button @click="saved = true">save</button> </div> `, beforeRouteLeave (route, redirect, next) { if (this.saved || window.confirm('Not saved, are you sure you want to navigate away?')) { next() } } } const router = new VueRouter({ mode: 'history', base: __dirname, routes: [ { path: '/', component: Home }, { path: '/baz', component: Baz } ] }) https://github.com/vuejs/vue-router/blob/next/examples/navigation-guards/app.js
  • 17. • Webpack will automatically split and lazy-load the split modules when using AMD require syntax Vue Router 2.0 - Async Components const Foo = resolve => require(['./Foo.vue'], resolve) const Bar = resolve => require(['./Bar.vue'], resolve) const router = new VueRouter({ mode: 'history', base: __dirname, routes: [ { path: '/', component: Home }, // Just use them normally in the route config { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ] }) https://github.com/vuejs/vue-router/blob/next/examples/lazy-loading/app.js
  • 18. • scrollBehavior • only available in html5 history mode • defaults to no scroll behavior • return false to prevent scroll Vue Router 2.0 - scrollBehavior const scrollBehavior = (to, from, savedPosition) => { if (savedPosition) { return savedPosition } else { const position = {} // new navigation. // scroll to anchor by returning the selector if (to.hash) { position.selector = to.hash } if (to.matched.some(m => m.meta.scrollToTop)) { // cords will be used if no selector is provided, // or if the selector didn't match any element. position.x = 0 position.y = 0 } // if the returned position is falsy or an empty object, // will retain current scroll position. return position } } const router = new VueRouter({ mode: 'history', base: __dirname, scrollBehavior, routes: [ { path: '/', component: Home, meta: { scrollToTop: true }}, { path: '/foo', component: Foo }, { path: '/bar', component: Bar, meta: { scrollToTop: true }} ] }) https://github.com/vuejs/vue-router/blob/next/examples/scroll-behavior/app.js
  • 19. • Transition • Dynamically transition setting on route change are available Vue Router 2.0 - Transition const Parent = { data () { return { transitionName: 'slide-left' } }, // dynamically set transition based on route change watch: { '$route' (to, from) { const toDepth = to.path.split('/').length const fromDepth = from.path.split('/').length this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left' } }, template: ` <div class="parent"> <h2>Parent</h2> <transition :name="transitionName"> <router-view class="child-view"></router-view> </transition> </div> ` } https://github.com/vuejs/vue-router/blob/next/examples/transitions/app.js
  • 20. • Vue Router x Vuex • Inject (sync) router states to Vuex states • Components can access router data (path, params, query) through vuex getter in components router • https://github.com/vuejs/vuex-router-sync Vue Router 2.0 - Vuex Router Sync
  • 21. SPA with Awesome Vue Family • Building SPA with Vue.js 2.0 Family • Better performance for SPA by reactive components mechanism • SSR & SPA with isomorphic fetch and client hydration • No worried about SEO & server side template like EJS • Seamless integration with Vue-Router & Vuex modules compare to React & React-Router & Redux because the author is same Evan :) It allows us more consistent & intuitive coding manner