SlideShare una empresa de Scribd logo
1 de 22
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/

Más contenido relacionado

La actualidad más candente

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 VueJsTudor 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.jsTakuya 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.JSEueung 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 routerKaty Slemon
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widgetTudor Barbu
 
Vue js and Vue Material
Vue js and Vue MaterialVue js and Vue Material
Vue js and Vue MaterialEueung Mulyana
 
以Vue開發電子商務網站
架構與眉角
以Vue開發電子商務網站
架構與眉角以Vue開發電子商務網站
架構與眉角
以Vue開發電子商務網站
架構與眉角Mei-yu Chen
 
第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]Kuro Hsu
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS IntroductionDavid Ličen
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & VuexBernd Alter
 
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.JSGalih Pratama
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting StartedMurat 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.jsZachary Klein
 
Vuejs for Angular developers
Vuejs for Angular developersVuejs for Angular developers
Vuejs for Angular developersMikhail 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 FrameworkHina Chen
 

La actualidad más candente (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 a 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.pdfKaty Slemon
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-senseBen 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 DjangoJavier Abadía
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applicationsAstrails
 
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.0Frost
 
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 2017Elyse 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 RailsJonathan 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 - mumbaiPraveen 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 ParisAhmed Radjdi
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.jsPagepro
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteorSapna 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.pptxBOSC 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
 
Introducing Vuex in your project
Introducing Vuex in your projectIntroducing Vuex in your project
Introducing Vuex in your projectDenny Biasiolli
 
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 VuexCommit University
 
Voorhoede - Front-end architecture
Voorhoede - Front-end architectureVoorhoede - Front-end architecture
Voorhoede - Front-end architectureJasper Moelker
 

Similar a 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
 
Introducing Vuex in your project
Introducing Vuex in your projectIntroducing Vuex in your project
Introducing Vuex in your project
 
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
 
Voorhoede - Front-end architecture
Voorhoede - Front-end architectureVoorhoede - Front-end architecture
Voorhoede - Front-end architecture
 

Más de Takuya Tejima

Nest.js Introduction
Nest.js IntroductionNest.js Introduction
Nest.js IntroductionTakuya Tejima
 
モダンフロントエンド開発者に求められるスキルとは
モダンフロントエンド開発者に求められるスキルとはモダンフロントエンド開発者に求められるスキルとは
モダンフロントエンド開発者に求められるスキルとはTakuya Tejima
 
Next.js Storybook Driven Development
Next.js Storybook Driven DevelopmentNext.js Storybook Driven Development
Next.js Storybook Driven DevelopmentTakuya Tejima
 
グローバルエンジニアキャリア はじめの一歩
グローバルエンジニアキャリア はじめの一歩グローバルエンジニアキャリア はじめの一歩
グローバルエンジニアキャリア はじめの一歩Takuya Tejima
 
GAOGAO発表資料〜エンジニアギルドミートアップ〜
GAOGAO発表資料〜エンジニアギルドミートアップ〜GAOGAO発表資料〜エンジニアギルドミートアップ〜
GAOGAO発表資料〜エンジニアギルドミートアップ〜Takuya Tejima
 
Laravel管理画面ジェネレーター
Laravel管理画面ジェネレーターLaravel管理画面ジェネレーター
Laravel管理画面ジェネレーターTakuya Tejima
 
エンジニア・コミュニティ・ドリブンで会社を成長させていくGAOGAO
エンジニア・コミュニティ・ドリブンで会社を成長させていくGAOGAOエンジニア・コミュニティ・ドリブンで会社を成長させていくGAOGAO
エンジニア・コミュニティ・ドリブンで会社を成長させていくGAOGAOTakuya 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 AsiaTakuya 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 handsonTakuya Tejima
 
Parseでちゃんとアプリを作るコツ
Parseでちゃんとアプリを作るコツParseでちゃんとアプリを作るコツ
Parseでちゃんとアプリを作るコツTakuya Tejima
 
React Canvasで作るFlappy Bird
React Canvasで作るFlappy BirdReact Canvasで作るFlappy Bird
React Canvasで作るFlappy BirdTakuya Tejima
 

Más de 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
 

Último

TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxPurva Nikam
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 

Último (20)

TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptx
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 

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