SlideShare a Scribd company logo
1 of 30
Vue 2.0
+
Vue Router & Vuex
Indie Inc. Co-founder & CTO
Takuya Tejima
Who
• Takuya Tejima @tejitak
• Co-founder & CTO at Indie Inc.
• Server & Web Front-end, iOS Engineer
• DevMorning community founder
• http://devmorning.connpass.com/
• Vue.js core team member
Vue.js MeetUp Tokyo!
• 2016/5/31
• Vue.js Tokyo v-meetup="#1"
• http://vuejs-
meetup.connpass.com/event/31139/
• Evan creator of Vue.js joined via Skype!
• He said “Vue.js is for everyone, not
for a company”
What is Vue.js
Vue Component Example
<template>
<div id="app">
<img src="./assets/logo.png">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
data () {
return {
msg: 'Hello Vue 2.0!'
}
}
}
</script>
<style>
body {
font-family: Helvetica, sans-serif;
}
</style>
Example of App.vue with webpack https://github.com/vuejs-templates/webpack-simple-2.0
Vue.js 2.0
Our JavaScript framework is
faster than React
rendering speed and memory consumption by up to 2-4x in m
ww.infoworld.com/article/3063615/javascript/vuejs-lead-our-javascript-framework-is-faster-than-re
Vue 2.0 Features
• Fast!
• Rendering layer is based on Snabbdom (a lightweight virtual-DOM implementation)
https://github.com/paldepind/snabbdom
• Compiler & Runtime are now separated
• Reactive!
• No need for shouldComponentUpdate / immutable
• Template ? JSX?
• You can use both with original template & new render function
• Sever Side Rendering! (Streaming SSR)
• NativeRendering
• Compatibility with v1.0
Vue 2.0 API Changes
• Lots of APIs are deprecated https://github.com/vuejs/vue/issues/2873
• Filter! (e.g. <span v-text="message | reverse"></span>)
• only available in text interpolations {{}}
• no build-in filters
• vm.$dispatch -> Vuex event bus
• vm.$appendTo -> Just use native DOM API
• v-for $index & $key -> (value, index) in arr, (value, key) in obj
• etc.
Rendering Implementations
• https://speakerdeck.com/kazupon/next-vue-dot-js-2-dot-0
Vue Router
Popular Frameworks for SPA Implementation
• How to implement a SPA (Single-page Application)
• Backbone, Ember, Riot, Angular + ui-router, Angular2, React +
React-Router (+ Redux), Vue.js + Vue-Router (+ Vuex)
• Important things to introduce
• Does your app really need to be a SPA?
• For example, do you need partial rendering?
• Choose framework depending on your app characteristics
What’s Vue-Router
• Creating a SPA with Vue.js + vue-router is dead simple
• Not only client-side routing (hash / history API), but also module based URL mapping
• Nested routes and sub components
• Async load
• etc.
• The following hooks are available
• data, activate, deactivate, canActivate, canDeactivate, canReuse
• NOTE The hooks will be changed to onEnter, onLeave, onChange in Vue-Router v0.8.0
• https://github.com/vuejs/vue-router/issues/321
Nested Routes and Sub Components & Hooks
Example URL change: /a/b/c -> /a/d/e
2. Validation phase
Check if all current components can be
activated / deactivated
3. Activation phase
Deactivate current components and activate new
components with data hook
1. Reusability phase
Check reusability
Code Example
main.vue
router.map({
'/about': {
component: require('./components/about.vue')
},
'/user/:userId': {
component: require('./components/user/index.vue'),
subRoutes: {
'profile/:something': {
component: require('./components/user/profile.vue')
}
},
'*': {
component: require('./components/not-found.vue')
},
})
app.vue
<template>
<div>
<p v-show="authenticating" style="color:red">Authenticating...</p>
<h1>App Header</h1>
<a v-link="{ path: '/about' }">about</a>
<a v-link="{ path: '/user/1234/profile/what' }">user</a>
<a v-link="{ path: '/mypage' }">mypage</a>
<router-view class="view" transition="test" transition-mode="out-in" keep-
alive></router-view>
</div>
</template>
components/user/index.vue
<template>
<div>
<h2>User yo</h2>
<router-view></router-view>
</div>
</template>
components/user/profile.vue
Authentication
router.beforeEach((transition) => {
if (transition.to.path === '/mypage') {
router.app.authenticating = true
// check if the user is authenticated
api.checkAuth().then(() => {
router.app.authenticating = false
// authentication success
transition.next()
}).catch(() => {
router.app.authenticating = false
// authentication failed
transition.abort()
})
} else {
transition.next()
}
})
Example auth page implementation with global before hook
Is Vue-Router Enough?
• If your SPA with Vue-Router has complex component state
structures, Vuex could be a solution
• Basically, more communications (e.g. dispatch &
broadcast) between components leads to unreadable
code
Vuex
Vuex
• Official redux inspired flux framework for Vue.js
• Vuex is more fit for Vue.js with efficient reactive system such as
data reactive rendering & components systems
Vuex
• Features
• Store
• basically a container that holds your application reactive states
• only way to change a store's state is by explicitly dispatching mutations
• Mutation
• sync (can not be async)
• split into modules with corresponding slice of the state
• Action
• dispatch mutations
• can be async
• Advantages
• simple unidirectional flow (less side effects)
• easy undo/redo - time travel
• hot reloading
• easy test
Vuex Flow Summary with Counter Example
Mutation Example
• Mutation (a name and a handler) mutates states with synchronous functions
• Vuex store's state is made reactive by Vue
• When we mutate the state, Vue components observing the state will update
automatically
import Vuex from 'vuex'
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
INCREMENT (state) {
// mutate state
state.count++
}
}
})
store.dispatch('INCREMENT')
• Must be called by dispatch in Action
What’s a Getter
• A getter provides accessing way to store data from components
• Components are not allowed to directly mutate a state
• It allows us to reuse computed methods (e.g. totals, averages) through a getter
- Getter Example
// getters.js
export function filteredMessages (state) {
return state.messages.filter(message => message.threadID === state.currentThreadID)
}
- Component
<script>
export default {
vuex: {
getters: {
filteredMessages
}
}
}
</script>
<template>
<div>
<ul>
<li v-for="msg in filteredMessages">{{mgs.title}}</li>
</ul>
</div>
</template>
NOTE the design may changed at Vuex 2.0
https://github.com/vuejs/vuex/issues/236
Vuex Form Handling
v-model directly rewrites store data. This is not the Vuex way (throws an error in strict
mode)
The Vuex way with v-model
- Set a getter value to form value
- Dispatch action by UI event (e.g. onclick)
Template:
<input :value="message" @input=“updateMessage”>
JS:
actions: {
updateMessage: ({ dispatch }, e) => {
dispatch('UPDATE_MESSAGE', e.target.value)
}
}
Dev Tools
https://github.com/vuejs/vue-devtools
Vue-Router + Vuex
Vue-router-sync
• 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
SPA with Awesome Vue Family
• If your application is not SPA just use Vue.js
• If your SPA …
• Needs mapping URL for components / partial rendering -> Vue Router
• Needs complex component state structure -> Vuex
• Needs both above -> Vuex + Vue Router + Vue Router Sync
Join Vue.js Community
• Vuejs-jp Skack
• https://vuejs-jp-slackin.herokuapp.com/
• Translations
• Vex docs are working in progress
• https://github.com/vuejs/vuex/pull/240
Thanks

More Related Content

What's hot

What's hot (20)

An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Vue, vue router, vuex
Vue, vue router, vuexVue, vue router, vuex
Vue, vue router, vuex
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting Started
 
Vue.js
Vue.jsVue.js
Vue.js
 
How to Build SPA with Vue Router 2.0
How to Build SPA with Vue Router 2.0How to Build SPA with Vue Router 2.0
How to Build SPA with Vue Router 2.0
 
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
 
Vue js 大型專案架構
Vue js 大型專案架構Vue js 大型專案架構
Vue js 大型專案架構
 
Vue.js
Vue.jsVue.js
Vue.js
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JS
 
Vue js for beginner
Vue js for beginner Vue js for beginner
Vue js for beginner
 
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
 
VueJS: The Simple Revolution
VueJS: The Simple RevolutionVueJS: The Simple Revolution
VueJS: The Simple Revolution
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.js
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
 
Vue 淺談前端建置工具
Vue 淺談前端建置工具Vue 淺談前端建置工具
Vue 淺談前端建置工具
 
第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]
 
Vue business first
Vue business firstVue business first
Vue business first
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & Vuex
 
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
 

Similar to Vue 2.0 + Vuex Router & Vuex at Vue.js

Introduction to web application development with Vue (for absolute beginners)...
Introduction to web application development with Vue (for absolute beginners)...Introduction to web application development with Vue (for absolute beginners)...
Introduction to web application development with Vue (for absolute beginners)...
Lucas Jellema
 
SoCal Code Camp 2011 - ASP.NET MVC 4
SoCal Code Camp 2011 - ASP.NET MVC 4SoCal Code Camp 2011 - ASP.NET MVC 4
SoCal Code Camp 2011 - ASP.NET MVC 4
Jon Galloway
 
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
DataArt
 

Similar to Vue 2.0 + Vuex Router & Vuex at Vue.js (20)

Drupal point of vue
Drupal point of vueDrupal point of vue
Drupal point of vue
 
Introduction to web application development with Vue (for absolute beginners)...
Introduction to web application development with Vue (for absolute beginners)...Introduction to web application development with Vue (for absolute beginners)...
Introduction to web application development with Vue (for absolute beginners)...
 
Vue js and Dyploma
Vue js and DyplomaVue js and Dyploma
Vue js and Dyploma
 
A New Vue for Web Development
A New Vue for Web DevelopmentA New Vue for Web Development
A New Vue for Web Development
 
MVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming modelMVC 6 - the new unified Web programming model
MVC 6 - the new unified Web programming model
 
JSS build and deployment
JSS build and deploymentJSS build and deployment
JSS build and deployment
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 
Oracle JavaScript Extension Toolkit Web Components Bring Agility to App Devel...
Oracle JavaScript Extension Toolkit Web Components Bring Agility to App Devel...Oracle JavaScript Extension Toolkit Web Components Bring Agility to App Devel...
Oracle JavaScript Extension Toolkit Web Components Bring Agility to App Devel...
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
ReactJS vs AngularJS - Head to Head comparison
ReactJS vs AngularJS - Head to Head comparisonReactJS vs AngularJS - Head to Head comparison
ReactJS vs AngularJS - Head to Head comparison
 
SoCal Code Camp 2011 - ASP.NET MVC 4
SoCal Code Camp 2011 - ASP.NET MVC 4SoCal Code Camp 2011 - ASP.NET MVC 4
SoCal Code Camp 2011 - ASP.NET MVC 4
 
Angular js 2.0
Angular js 2.0Angular js 2.0
Angular js 2.0
 
Asp.net,mvc
Asp.net,mvcAsp.net,mvc
Asp.net,mvc
 
Vincent biret azure functions and flow (ottawa)
Vincent biret azure functions and flow (ottawa)Vincent biret azure functions and flow (ottawa)
Vincent biret azure functions and flow (ottawa)
 
Vincent biret azure functions and flow (toronto)
Vincent biret azure functions and flow (toronto)Vincent biret azure functions and flow (toronto)
Vincent biret azure functions and flow (toronto)
 
Vue Storefront - Progressive Web App for Magento (1.9, 2.x) - MM18DE speech
Vue Storefront - Progressive Web App for Magento (1.9, 2.x) - MM18DE speechVue Storefront - Progressive Web App for Magento (1.9, 2.x) - MM18DE speech
Vue Storefront - Progressive Web App for Magento (1.9, 2.x) - MM18DE speech
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
 
Vue.js - An Introduction
Vue.js - An IntroductionVue.js - An Introduction
Vue.js - An Introduction
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
 

More from 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

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Dr.Costas Sachpazis
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 

Recently uploaded (20)

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 

Vue 2.0 + Vuex Router & Vuex at Vue.js

  • 1. Vue 2.0 + Vue Router & Vuex Indie Inc. Co-founder & CTO Takuya Tejima
  • 2. Who • Takuya Tejima @tejitak • Co-founder & CTO at Indie Inc. • Server & Web Front-end, iOS Engineer • DevMorning community founder • http://devmorning.connpass.com/ • Vue.js core team member
  • 3. Vue.js MeetUp Tokyo! • 2016/5/31 • Vue.js Tokyo v-meetup="#1" • http://vuejs- meetup.connpass.com/event/31139/ • Evan creator of Vue.js joined via Skype! • He said “Vue.js is for everyone, not for a company”
  • 5. Vue Component Example <template> <div id="app"> <img src="./assets/logo.png"> <h1>{{ msg }}</h1> </div> </template> <script> export default { data () { return { msg: 'Hello Vue 2.0!' } } } </script> <style> body { font-family: Helvetica, sans-serif; } </style> Example of App.vue with webpack https://github.com/vuejs-templates/webpack-simple-2.0
  • 7. Our JavaScript framework is faster than React rendering speed and memory consumption by up to 2-4x in m ww.infoworld.com/article/3063615/javascript/vuejs-lead-our-javascript-framework-is-faster-than-re
  • 8. Vue 2.0 Features • Fast! • Rendering layer is based on Snabbdom (a lightweight virtual-DOM implementation) https://github.com/paldepind/snabbdom • Compiler & Runtime are now separated • Reactive! • No need for shouldComponentUpdate / immutable • Template ? JSX? • You can use both with original template & new render function • Sever Side Rendering! (Streaming SSR) • NativeRendering • Compatibility with v1.0
  • 9. Vue 2.0 API Changes • Lots of APIs are deprecated https://github.com/vuejs/vue/issues/2873 • Filter! (e.g. <span v-text="message | reverse"></span>) • only available in text interpolations {{}} • no build-in filters • vm.$dispatch -> Vuex event bus • vm.$appendTo -> Just use native DOM API • v-for $index & $key -> (value, index) in arr, (value, key) in obj • etc.
  • 12. Popular Frameworks for SPA Implementation • How to implement a SPA (Single-page Application) • Backbone, Ember, Riot, Angular + ui-router, Angular2, React + React-Router (+ Redux), Vue.js + Vue-Router (+ Vuex) • Important things to introduce • Does your app really need to be a SPA? • For example, do you need partial rendering? • Choose framework depending on your app characteristics
  • 13. What’s Vue-Router • Creating a SPA with Vue.js + vue-router is dead simple • Not only client-side routing (hash / history API), but also module based URL mapping • Nested routes and sub components • Async load • etc. • The following hooks are available • data, activate, deactivate, canActivate, canDeactivate, canReuse • NOTE The hooks will be changed to onEnter, onLeave, onChange in Vue-Router v0.8.0 • https://github.com/vuejs/vue-router/issues/321
  • 14. Nested Routes and Sub Components & Hooks Example URL change: /a/b/c -> /a/d/e 2. Validation phase Check if all current components can be activated / deactivated 3. Activation phase Deactivate current components and activate new components with data hook 1. Reusability phase Check reusability
  • 15. Code Example main.vue router.map({ '/about': { component: require('./components/about.vue') }, '/user/:userId': { component: require('./components/user/index.vue'), subRoutes: { 'profile/:something': { component: require('./components/user/profile.vue') } }, '*': { component: require('./components/not-found.vue') }, }) app.vue <template> <div> <p v-show="authenticating" style="color:red">Authenticating...</p> <h1>App Header</h1> <a v-link="{ path: '/about' }">about</a> <a v-link="{ path: '/user/1234/profile/what' }">user</a> <a v-link="{ path: '/mypage' }">mypage</a> <router-view class="view" transition="test" transition-mode="out-in" keep- alive></router-view> </div> </template> components/user/index.vue <template> <div> <h2>User yo</h2> <router-view></router-view> </div> </template> components/user/profile.vue
  • 16. Authentication router.beforeEach((transition) => { if (transition.to.path === '/mypage') { router.app.authenticating = true // check if the user is authenticated api.checkAuth().then(() => { router.app.authenticating = false // authentication success transition.next() }).catch(() => { router.app.authenticating = false // authentication failed transition.abort() }) } else { transition.next() } }) Example auth page implementation with global before hook
  • 17. Is Vue-Router Enough? • If your SPA with Vue-Router has complex component state structures, Vuex could be a solution • Basically, more communications (e.g. dispatch & broadcast) between components leads to unreadable code
  • 18. Vuex
  • 19. Vuex • Official redux inspired flux framework for Vue.js • Vuex is more fit for Vue.js with efficient reactive system such as data reactive rendering & components systems
  • 20. Vuex • Features • Store • basically a container that holds your application reactive states • only way to change a store's state is by explicitly dispatching mutations • Mutation • sync (can not be async) • split into modules with corresponding slice of the state • Action • dispatch mutations • can be async • Advantages • simple unidirectional flow (less side effects) • easy undo/redo - time travel • hot reloading • easy test
  • 21. Vuex Flow Summary with Counter Example
  • 22. Mutation Example • Mutation (a name and a handler) mutates states with synchronous functions • Vuex store's state is made reactive by Vue • When we mutate the state, Vue components observing the state will update automatically import Vuex from 'vuex' const store = new Vuex.Store({ state: { count: 1 }, mutations: { INCREMENT (state) { // mutate state state.count++ } } }) store.dispatch('INCREMENT') • Must be called by dispatch in Action
  • 23. What’s a Getter • A getter provides accessing way to store data from components • Components are not allowed to directly mutate a state • It allows us to reuse computed methods (e.g. totals, averages) through a getter - Getter Example // getters.js export function filteredMessages (state) { return state.messages.filter(message => message.threadID === state.currentThreadID) } - Component <script> export default { vuex: { getters: { filteredMessages } } } </script> <template> <div> <ul> <li v-for="msg in filteredMessages">{{mgs.title}}</li> </ul> </div> </template> NOTE the design may changed at Vuex 2.0 https://github.com/vuejs/vuex/issues/236
  • 24. Vuex Form Handling v-model directly rewrites store data. This is not the Vuex way (throws an error in strict mode) The Vuex way with v-model - Set a getter value to form value - Dispatch action by UI event (e.g. onclick) Template: <input :value="message" @input=“updateMessage”> JS: actions: { updateMessage: ({ dispatch }, e) => { dispatch('UPDATE_MESSAGE', e.target.value) } }
  • 27. Vue-router-sync • 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
  • 28. SPA with Awesome Vue Family • If your application is not SPA just use Vue.js • If your SPA … • Needs mapping URL for components / partial rendering -> Vue Router • Needs complex component state structure -> Vuex • Needs both above -> Vuex + Vue Router + Vue Router Sync
  • 29. Join Vue.js Community • Vuejs-jp Skack • https://vuejs-jp-slackin.herokuapp.com/ • Translations • Vex docs are working in progress • https://github.com/vuejs/vuex/pull/240