SlideShare une entreprise Scribd logo
1  sur  38
Télécharger pour lire hors ligne
Modern frontend development
with Vue JS
Tudor Barbu
@motanelu
www.linkedin.com/in/tudorbarbu
https://github.com/motanelu
How old are
you? :)
Tools provided by early JS frameworks:
● AJAX abstractions
● Simple DOM manipulation
● Event management
● Annoying animations
● Shorthand methods*
Paleolithic 2.0
* not really a good thing
Missing pieces
● DOM abstractions / templating
● URL management / routing
● State management
● Support for reusable components
● Coding standard and guidelines
$(document).ready(function () {
$('#refresh-button').click(function () {
$('#news-container').load('/latest-news')
})
})
$(function () {
$('#refresh-button').on('click', function () {
$.ajax('/latest-news', {
success: function (data, textStatus, jqXHR) {
var html = createHTMLFromJsonResponse(data)
$('#news-container').html(html)
}
})
})
})
Inconsistent event handling
Inefficient DOM operations
<div class="article" id="article-5">
<h2>The awesome title</h2>
<p>
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Donec hendrerit nunc
turpis, quis maximus egestas sit amet.
</p>
<span class="likes">2<span>
</div>
/* content at t1 (initial state) */
article = {
id: '5',
title: 'The awesome title',
content: 'Lorem ipsum dolor sit amet...',
likes: 2
}
/* content at t2 (after update) */
article = {
id: '5',
title: 'The awesome title',
content: 'Lorem ipsum dolor sit amet...',
likes: 4
}
Virtual DOM
diff
patch
<ul class="product-menu">
<li data-item-id="65017da4">Product one</li>
<li data-item-id="6501816e">Product two</li>
</ul>
$('.product-menu').on('click', 'li', function () {
var id = $(this).data('item-id')
loadProduct(id)
})
Keeping state in the DOM
(slow)
<ul class="menu">
<li data-href="index">Home</li>
<li data-href="contact">Contact</li>
</ul>
<div id="page-content">
<!-- content loaded via AJAX -->
<form id="content-form">
<!-- ... fields ...-->
<button type="button" class="submit">
Contact us
</button>
</form>
</div>
$('#content-form .submit').click(function () {
var form = $('#content-form')
var isValid = validate(form)
if (isValid) {
postTheForm(form)
}
})
Where do I fit in?
Every Javascript project
after 6 to 9 months
When your framework is just right:
● Separation of concerns
● Virtual DOM
● In memory state management
● Routing (HTML5 History API)
● Clear coding practices
● AJAX (nice to have)
Why Vue.js?
● Lightweight
● “True” open-source
● Fastest learning curve
● Separation of concerns in one file
● Great performance per KB *
* just invented this metric
DOM operations performance
Source: http://www.stefankrause.net/js-frameworks-benchmark6/webdriver-ts-results/table.html
Sources:
1. http://www.stefankrause.net/js-frameworks-benchmark6/webdriver-ts-results/table.html
2. https://gist.github.com/Restuta/cda69e50a853aa64912d
RAM usage & filesize
Components
Content.vue
Footer.vue
MenuItem.vue
selected
Components are
● Custom HTML elements with behaviour attached to
them
● Self-contained
● Reside in .vue files (compiled with Webpack)
● Can be mixed with regular HTML
● The Vue application is wrapped in a root
component, usually called App.vue
<template>
<div class="content">
<div v-if="loaded">
<h1>{{ title }}</h1>
<img :src="media" :alt="title">
<p>{{ article }}</p>
</div>
<div v-else>Loading...</div>
</div>
</template>
<script>
export default {
name: 'content',
data () {
return {
loaded: false,
title: null,
article: null,
media: null
}
},
mounted () {
axios.get('/latest-news').then(response => {
this.title = response.data.title,
this.article = response.data.article
this.media = response.data.media
this.loaded = true
})
}
}
</script>
<style>
h1 {
font-family: "Comic Sans" /* on purpose :) */
}
</style>
“Reactive” properties
Lifecycle events
HTML template
presentation logic
CSS styling
Javascript part
component logic
Content.vue
<!-- ... -->
<div v-if="loaded">
<h1>{{ title }}</h1>
<img :src="media" :alt="title">
</div>
<!-- ... -->
/* ... */
data () {
return {
loaded: false,
title: null,
media: null
}
}
/* ... */
show / hide elements
fill in HTML elements
values for HTML attributes
Reactive properties
Changing a reactive property triggers a re-render of the associated DOM
<template>
<div class="content">
<div v-if="loaded">
<h1>{{ title }}</h1>
<p>{{ article }}</p>
</div>
<div v-else>
Loading...
</div>
</div>
</template>
<script>
export default {
name: 'content',
data () {
return {
title: null,
article: null
}
},
computed: {
loaded () {
return title !== null && article !== null
}
},
mounted () {
// ...
}
}
</script>
<style>
h1 {
font-family: "Comic Sans" /* on purpose :) */
}
</style>
Computed properties
Computed properties:
● Functions that wrap complex logic
● Cached based on their dependencies
<template>
<!-- display article -->
<a href="#" v-on:click="toggle()">{{ toggleMessage }}</a>
<div v-if="showRelated">
<ul>
<li v-for="article in related">
<a href="{{ article.url }}"> {{ article.text }}</a>
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'content',
data () {
return {
/* ... */
showRelated: false,
related: [
{ url: '/path/to/first-article', text: 'First related article' },
{ url: '/path/to/second-article', text: 'Second related article' }
]
}
},
computed: {
toggleMessage () {
return !this.showRelated ? 'Show related articles' : 'Hide related articles'
}
},
methods: {
toggle() {
this.showRelated = !this.showRelated
}
}
}
</script>
Iterate through properties
HTML-like syntax for
event handlers
Computed properties can
be anything
HTML event handlers!?!
● Easier to locate handlers just by skimming the template
● Easier to test the underlying logic since it’s completely separated
from the DOM
● They can be automatically removed together with their associated
HTML code
<template>
<header>
<ul>
<menu-item id="1" label="books" />
<menu-item id="2" label="pens" />
</ul>
<header>
<div class="main">
<content>
</div>
<footer>
</template>
<script>
import MenuItem from '/path/to/MenuItem.vue'
import Content from '/path/to/Content.vue'
import Footer from '/path/to/Footer.vue'
export default {
name: 'app',
components: {
'menu-item': MenuItem,
'content': Content
'footer': Footer
}
/* ... */
}
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App />',
components: { App }
})
App.vue main.js
Components
usage
Parent
Child
publishevents
injectproperties
2 Way data communication
● Parents inject values via HTML attributes
● Children push custom events using the
v-on:{custom-event} format
<template>
<ul>
<menu-item
id="1"
label="books"
v-on:selected="process($event)" />
<menu-item
id="2"
label="pens"
selected="true""
v-on:selected="process($event) />
</ul>
</template>
<script>
import MenuItem from './path/to/MenuItem.vue'
export default {
name: 'top-menu',
components: {
'menu-item': MenuItem
},
methods: {
process ($event) {
// select the category
}
}
}
</script>
<template>
<li :class="{'active-element': selected}">
<a v-on:click="select()">
{{ label }}
</a>
</li>
</template>
<script>
export default {
name: 'MenuItem',
props: ['id', 'label', 'selected'],
methods: {
select () {
this.$emit('selected', { id: this.id })
}
}
}
</script>
Properties
Events
App.vue MenuItem.vue
/* Content.vue */
export default {
/* ... */
data () {
return {
title: null,
article: null
}
},
computed: {
loaded () {
return article !== null && title !== null
}
},
props: [
'articleId'
],
watch: {
articleId: (value, previous) {
axios.get(`/article/{$value}`).then(response => {
this.title = response.data.title,
this.article = response.data.article
})
}
}
}
<!-- App.vue -->
<template>
<ul class="menu">
<li v-on:click="loadArticle(1)">
First article
</li>
<li v-on:click="loadArticle(2)">
Second article
</li>
<!-- ... -->
</ul>
<content :articleId="articleId" />
</template>
<script>
/* ... */
export default {
data () {
return {
articleId: null
}
},
methods: {
loadArticle(articleId) {
this.articleId = articleId
}
}
}
</script>
Reactive properties
Changes on the articleId are propagated
to the child
Encapsulated functionality
Everything about loading and
processing the content is encapsulated
$ npm install vue-router --save
Not this kind of router :)
Vue Router
Vue Routing
● Provides stateful URLs
● Supports both HTML5 history API as well as the # as
fallback
import Vue from 'vue'
import Router from 'vue-router'
import Homepage from '/path/Home.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Homepage
}
]
})
import Vue from 'vue'
import router from '/path/to/router'
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App />',
components: { App }
})
<template>
<!-- App.vue -->
<router-view />
</template>
1 2 3
router.js main.js App.vue
Other features:
● dynamic routes (/article/:id)
● nested routes
● programmatic navigation
● allows adding watchers on routes
Image from https://vuex.vuejs.org/en/intro.html
$ npm install vuex --save
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const FETCH_START = 'FETCH_START'
const FETCH_SUCCESS = 'FETCH_SUCCESS'
const FETCH_ERROR = 'FETCH_ERROR'
export default new Vuex.Store ({
state: {
loading: false,
error: null,
article: null
},
mutations: {
[FETCH_START](state) {
state.loading = true
state.error = null
},
[FETCH_SUCCESS](state, article) {
state.error = null
state.loading = false
state.article = article
},
[FETCH_ERROR](state) {
state.loading = false
state.error = true
}
},
actions: {
load({ commit }, { articleId }) {
commit(FETCH_START)
axios.get(`/articles/${articleId}`)
.then(article => commit(FETCH_SUCCESS, article))
.catch(() => commit(FETCH_ERROR))
}
}
})
Constants for mutation types
(common pattern)
State variables
Mutations
(need to be synchronous)
Vuexmodule
Actions
(can be asynchronous & they end
with a mutation)
<template>
<ul class="menu">
<li v-on:click="loadArticle(1)">
First article
</li>
<li v-on:click="loadArticle(2)">
Second article
</li>
<!-- ... -->
</ul>
<content />
</template>
<script>
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions({
'loadArticle': 'load'
}),
// other component specific methods
}
}
</script>
UsingVuex
Map Vuex actions in the local scope
( mapAction helper & spread operator)
Templates stay the same
Vuex
Menu.vue
(update selected item)
Content.vue
(display the content)
Breadcrumbs.vue
(display the current node)
App.vue
(update the <title>)
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
loading: state => state.loading,
error: state => state.error,
article: state => state.article
})
},
watch: {
article: (value, previous) {
// trigger an update
}
error: (value) {
if (value) {
// signal an error to the user
}
}
}
}
HTML event handlers!?!
● Efficient DOM manipulation with Virtual DOM
●
● lightweight
● efficient DOM manipulation
● separation of concerns & encapsulation
● routing (HTML5 History API & hash sign)
● state management with Vuex
$ npm install -g vue-cli
$ vue init webpack my-first-vue-project
Vue CLI
● Quickly start a new project
● Multiple templates and build systems *
● Sets up linters (AirBNB or Standard)
● Unit tests (karma)
● End to end tests (Nightwatch)
* if in doubt, use Webpack
https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en
Features
● Inspect components in real
time
● Inspect Vuex status
● “Timetravel” between Vuex
commits
Resources
● vuejs.org
● router.vuejs.org
● vuex.vuejs.org
● vuejs/awesome-vue
Thank you
@Schibsted_Eng
bytes.schibsted.com
Tudor Barbu
@motanelu
www.linkedin.com/in/tudorbarbu
https://github.com/motanelu

Contenu connexe

Tendances

Drupal point of vue
Drupal point of vueDrupal point of vue
Drupal point of vueDavid Ličen
 
An Introduction to Vuejs
An Introduction to VuejsAn Introduction to Vuejs
An Introduction to VuejsPaddy Lock
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & VuexBernd Alter
 
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.0Takuya Tejima
 
Testing frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTesting frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTudor Barbu
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting StartedMurat Doğan
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.jsTechExeter
 
Introduction to modern front-end with Vue.js
Introduction to modern front-end with Vue.jsIntroduction to modern front-end with Vue.js
Introduction to modern front-end with Vue.jsmonterail
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.jsPagepro
 
Nuxt.JS Introdruction
Nuxt.JS IntrodructionNuxt.JS Introdruction
Nuxt.JS IntrodructionDavid Ličen
 
Vue.js is boring - and that's a good thing
Vue.js is boring - and that's a good thingVue.js is boring - and that's a good thing
Vue.js is boring - and that's a good thingJoonas Lehtonen
 
Building a Startup Stack with AngularJS
Building a Startup Stack with AngularJSBuilding a Startup Stack with AngularJS
Building a Startup Stack with AngularJSFITC
 
Vue js 大型專案架構
Vue js 大型專案架構Vue js 大型專案架構
Vue js 大型專案架構Hina Chen
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3 ArezooKmn
 
Grails Launchpad - From Ground Zero to Orbit
Grails Launchpad - From Ground Zero to OrbitGrails Launchpad - From Ground Zero to Orbit
Grails Launchpad - From Ground Zero to OrbitZachary Klein
 

Tendances (20)

Drupal point of vue
Drupal point of vueDrupal point of vue
Drupal point of vue
 
Vue.js
Vue.jsVue.js
Vue.js
 
An Introduction to Vuejs
An Introduction to VuejsAn Introduction to Vuejs
An Introduction to Vuejs
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & Vuex
 
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
 
Love at first Vue
Love at first VueLove at first Vue
Love at first Vue
 
Testing frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTesting frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabs
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting Started
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.js
 
Introduction to modern front-end with Vue.js
Introduction to modern front-end with Vue.jsIntroduction to modern front-end with Vue.js
Introduction to modern front-end with Vue.js
 
Vuex
VuexVuex
Vuex
 
Intro to Vue
Intro to Vue Intro to Vue
Intro to Vue
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Nuxt.JS Introdruction
Nuxt.JS IntrodructionNuxt.JS Introdruction
Nuxt.JS Introdruction
 
Vue.js is boring - and that's a good thing
Vue.js is boring - and that's a good thingVue.js is boring - and that's a good thing
Vue.js is boring - and that's a good thing
 
Building a Startup Stack with AngularJS
Building a Startup Stack with AngularJSBuilding a Startup Stack with AngularJS
Building a Startup Stack with AngularJS
 
Vue js 大型專案架構
Vue js 大型專案架構Vue js 大型專案架構
Vue js 大型專案架構
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
Vue presentation
Vue presentationVue presentation
Vue presentation
 
Grails Launchpad - From Ground Zero to Orbit
Grails Launchpad - From Ground Zero to OrbitGrails Launchpad - From Ground Zero to Orbit
Grails Launchpad - From Ground Zero to Orbit
 

Similaire à Modern frontend development with VueJs

Creating lightweight JS Apps w/ Web Components and lit-html
Creating lightweight JS Apps w/ Web Components and lit-htmlCreating lightweight JS Apps w/ Web Components and lit-html
Creating lightweight JS Apps w/ Web Components and lit-htmlIlia Idakiev
 
Frontend meetup 2014.06.25
Frontend meetup 2014.06.25Frontend meetup 2014.06.25
Frontend meetup 2014.06.25EU Edge
 
Webcomponents at Frontend meetup 2014.06.25
Webcomponents at Frontend meetup 2014.06.25Webcomponents at Frontend meetup 2014.06.25
Webcomponents at Frontend meetup 2014.06.25Robert Szaloki
 
Web Components v1
Web Components v1Web Components v1
Web Components v1Mike Wilcox
 
Desbravando Web Components
Desbravando Web ComponentsDesbravando Web Components
Desbravando Web ComponentsMateus Ortiz
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest servicesIoan Eugen Stan
 
Interoperable Component Patterns
Interoperable Component PatternsInteroperable Component Patterns
Interoperable Component PatternsMatthew Beale
 
Modern Web Technologies
Modern Web TechnologiesModern Web Technologies
Modern Web TechnologiesPerttu Myry
 
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Luciano Mammino
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalystsvilen.ivanov
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting startedMoniaJ
 
The Future of the Web
The Future of the WebThe Future of the Web
The Future of the WebRay Nicholus
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoRob Bontekoe
 
Academy PRO: React JS
Academy PRO: React JSAcademy PRO: React JS
Academy PRO: React JSBinary Studio
 
JavaScript: DOM and jQuery
JavaScript: DOM and jQueryJavaScript: DOM and jQuery
JavaScript: DOM and jQuery維佋 唐
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2Paras Mendiratta
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 

Similaire à Modern frontend development with VueJs (20)

Creating lightweight JS Apps w/ Web Components and lit-html
Creating lightweight JS Apps w/ Web Components and lit-htmlCreating lightweight JS Apps w/ Web Components and lit-html
Creating lightweight JS Apps w/ Web Components and lit-html
 
Frontend meetup 2014.06.25
Frontend meetup 2014.06.25Frontend meetup 2014.06.25
Frontend meetup 2014.06.25
 
Webcomponents at Frontend meetup 2014.06.25
Webcomponents at Frontend meetup 2014.06.25Webcomponents at Frontend meetup 2014.06.25
Webcomponents at Frontend meetup 2014.06.25
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
 
Desbravando Web Components
Desbravando Web ComponentsDesbravando Web Components
Desbravando Web Components
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
 
Interoperable Component Patterns
Interoperable Component PatternsInteroperable Component Patterns
Interoperable Component Patterns
 
Modern Web Technologies
Modern Web TechnologiesModern Web Technologies
Modern Web Technologies
 
React js
React jsReact js
React js
 
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
 
The Future of the Web
The Future of the WebThe Future of the Web
The Future of the Web
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" Domino
 
Academy PRO: React JS
Academy PRO: React JSAcademy PRO: React JS
Academy PRO: React JS
 
JavaScript: DOM and jQuery
JavaScript: DOM and jQueryJavaScript: DOM and jQuery
JavaScript: DOM and jQuery
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2
 
前端概述
前端概述前端概述
前端概述
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 

Dernier

A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
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 Performancesivaprakash250
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf203318pmpc
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
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 engineeringmulugeta48
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projectssmsksolar
 
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.pdfKamal Acharya
 

Dernier (20)

(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
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
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
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
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
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
 

Modern frontend development with VueJs

  • 1. Modern frontend development with Vue JS Tudor Barbu @motanelu www.linkedin.com/in/tudorbarbu https://github.com/motanelu
  • 2.
  • 4. Tools provided by early JS frameworks: ● AJAX abstractions ● Simple DOM manipulation ● Event management ● Annoying animations ● Shorthand methods* Paleolithic 2.0 * not really a good thing
  • 5. Missing pieces ● DOM abstractions / templating ● URL management / routing ● State management ● Support for reusable components ● Coding standard and guidelines
  • 6. $(document).ready(function () { $('#refresh-button').click(function () { $('#news-container').load('/latest-news') }) }) $(function () { $('#refresh-button').on('click', function () { $.ajax('/latest-news', { success: function (data, textStatus, jqXHR) { var html = createHTMLFromJsonResponse(data) $('#news-container').html(html) } }) }) }) Inconsistent event handling Inefficient DOM operations
  • 7. <div class="article" id="article-5"> <h2>The awesome title</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit nunc turpis, quis maximus egestas sit amet. </p> <span class="likes">2<span> </div> /* content at t1 (initial state) */ article = { id: '5', title: 'The awesome title', content: 'Lorem ipsum dolor sit amet...', likes: 2 } /* content at t2 (after update) */ article = { id: '5', title: 'The awesome title', content: 'Lorem ipsum dolor sit amet...', likes: 4 } Virtual DOM diff patch
  • 8. <ul class="product-menu"> <li data-item-id="65017da4">Product one</li> <li data-item-id="6501816e">Product two</li> </ul> $('.product-menu').on('click', 'li', function () { var id = $(this).data('item-id') loadProduct(id) }) Keeping state in the DOM (slow) <ul class="menu"> <li data-href="index">Home</li> <li data-href="contact">Contact</li> </ul> <div id="page-content"> <!-- content loaded via AJAX --> <form id="content-form"> <!-- ... fields ...--> <button type="button" class="submit"> Contact us </button> </form> </div> $('#content-form .submit').click(function () { var form = $('#content-form') var isValid = validate(form) if (isValid) { postTheForm(form) } }) Where do I fit in?
  • 10. When your framework is just right: ● Separation of concerns ● Virtual DOM ● In memory state management ● Routing (HTML5 History API) ● Clear coding practices ● AJAX (nice to have)
  • 11.
  • 12. Why Vue.js? ● Lightweight ● “True” open-source ● Fastest learning curve ● Separation of concerns in one file ● Great performance per KB * * just invented this metric
  • 13. DOM operations performance Source: http://www.stefankrause.net/js-frameworks-benchmark6/webdriver-ts-results/table.html
  • 16. Content.vue Footer.vue MenuItem.vue selected Components are ● Custom HTML elements with behaviour attached to them ● Self-contained ● Reside in .vue files (compiled with Webpack) ● Can be mixed with regular HTML ● The Vue application is wrapped in a root component, usually called App.vue
  • 17. <template> <div class="content"> <div v-if="loaded"> <h1>{{ title }}</h1> <img :src="media" :alt="title"> <p>{{ article }}</p> </div> <div v-else>Loading...</div> </div> </template> <script> export default { name: 'content', data () { return { loaded: false, title: null, article: null, media: null } }, mounted () { axios.get('/latest-news').then(response => { this.title = response.data.title, this.article = response.data.article this.media = response.data.media this.loaded = true }) } } </script> <style> h1 { font-family: "Comic Sans" /* on purpose :) */ } </style> “Reactive” properties Lifecycle events HTML template presentation logic CSS styling Javascript part component logic Content.vue
  • 18. <!-- ... --> <div v-if="loaded"> <h1>{{ title }}</h1> <img :src="media" :alt="title"> </div> <!-- ... --> /* ... */ data () { return { loaded: false, title: null, media: null } } /* ... */ show / hide elements fill in HTML elements values for HTML attributes Reactive properties Changing a reactive property triggers a re-render of the associated DOM
  • 19. <template> <div class="content"> <div v-if="loaded"> <h1>{{ title }}</h1> <p>{{ article }}</p> </div> <div v-else> Loading... </div> </div> </template> <script> export default { name: 'content', data () { return { title: null, article: null } }, computed: { loaded () { return title !== null && article !== null } }, mounted () { // ... } } </script> <style> h1 { font-family: "Comic Sans" /* on purpose :) */ } </style> Computed properties Computed properties: ● Functions that wrap complex logic ● Cached based on their dependencies
  • 20. <template> <!-- display article --> <a href="#" v-on:click="toggle()">{{ toggleMessage }}</a> <div v-if="showRelated"> <ul> <li v-for="article in related"> <a href="{{ article.url }}"> {{ article.text }}</a> </li> </ul> </div> </template> <script> export default { name: 'content', data () { return { /* ... */ showRelated: false, related: [ { url: '/path/to/first-article', text: 'First related article' }, { url: '/path/to/second-article', text: 'Second related article' } ] } }, computed: { toggleMessage () { return !this.showRelated ? 'Show related articles' : 'Hide related articles' } }, methods: { toggle() { this.showRelated = !this.showRelated } } } </script> Iterate through properties HTML-like syntax for event handlers Computed properties can be anything
  • 21. HTML event handlers!?! ● Easier to locate handlers just by skimming the template ● Easier to test the underlying logic since it’s completely separated from the DOM ● They can be automatically removed together with their associated HTML code
  • 22. <template> <header> <ul> <menu-item id="1" label="books" /> <menu-item id="2" label="pens" /> </ul> <header> <div class="main"> <content> </div> <footer> </template> <script> import MenuItem from '/path/to/MenuItem.vue' import Content from '/path/to/Content.vue' import Footer from '/path/to/Footer.vue' export default { name: 'app', components: { 'menu-item': MenuItem, 'content': Content 'footer': Footer } /* ... */ } import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', template: '<App />', components: { App } }) App.vue main.js Components usage
  • 23. Parent Child publishevents injectproperties 2 Way data communication ● Parents inject values via HTML attributes ● Children push custom events using the v-on:{custom-event} format
  • 24. <template> <ul> <menu-item id="1" label="books" v-on:selected="process($event)" /> <menu-item id="2" label="pens" selected="true"" v-on:selected="process($event) /> </ul> </template> <script> import MenuItem from './path/to/MenuItem.vue' export default { name: 'top-menu', components: { 'menu-item': MenuItem }, methods: { process ($event) { // select the category } } } </script> <template> <li :class="{'active-element': selected}"> <a v-on:click="select()"> {{ label }} </a> </li> </template> <script> export default { name: 'MenuItem', props: ['id', 'label', 'selected'], methods: { select () { this.$emit('selected', { id: this.id }) } } } </script> Properties Events App.vue MenuItem.vue
  • 25. /* Content.vue */ export default { /* ... */ data () { return { title: null, article: null } }, computed: { loaded () { return article !== null && title !== null } }, props: [ 'articleId' ], watch: { articleId: (value, previous) { axios.get(`/article/{$value}`).then(response => { this.title = response.data.title, this.article = response.data.article }) } } }
  • 26. <!-- App.vue --> <template> <ul class="menu"> <li v-on:click="loadArticle(1)"> First article </li> <li v-on:click="loadArticle(2)"> Second article </li> <!-- ... --> </ul> <content :articleId="articleId" /> </template> <script> /* ... */ export default { data () { return { articleId: null } }, methods: { loadArticle(articleId) { this.articleId = articleId } } } </script> Reactive properties Changes on the articleId are propagated to the child Encapsulated functionality Everything about loading and processing the content is encapsulated
  • 27. $ npm install vue-router --save Not this kind of router :) Vue Router Vue Routing ● Provides stateful URLs ● Supports both HTML5 history API as well as the # as fallback
  • 28. import Vue from 'vue' import Router from 'vue-router' import Homepage from '/path/Home.vue' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Home', component: Homepage } ] }) import Vue from 'vue' import router from '/path/to/router' /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<App />', components: { App } }) <template> <!-- App.vue --> <router-view /> </template> 1 2 3 router.js main.js App.vue Other features: ● dynamic routes (/article/:id) ● nested routes ● programmatic navigation ● allows adding watchers on routes
  • 29. Image from https://vuex.vuejs.org/en/intro.html $ npm install vuex --save import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex)
  • 30. const FETCH_START = 'FETCH_START' const FETCH_SUCCESS = 'FETCH_SUCCESS' const FETCH_ERROR = 'FETCH_ERROR' export default new Vuex.Store ({ state: { loading: false, error: null, article: null }, mutations: { [FETCH_START](state) { state.loading = true state.error = null }, [FETCH_SUCCESS](state, article) { state.error = null state.loading = false state.article = article }, [FETCH_ERROR](state) { state.loading = false state.error = true } }, actions: { load({ commit }, { articleId }) { commit(FETCH_START) axios.get(`/articles/${articleId}`) .then(article => commit(FETCH_SUCCESS, article)) .catch(() => commit(FETCH_ERROR)) } } }) Constants for mutation types (common pattern) State variables Mutations (need to be synchronous) Vuexmodule Actions (can be asynchronous & they end with a mutation)
  • 31. <template> <ul class="menu"> <li v-on:click="loadArticle(1)"> First article </li> <li v-on:click="loadArticle(2)"> Second article </li> <!-- ... --> </ul> <content /> </template> <script> import { mapActions } from 'vuex' export default { methods: { ...mapActions({ 'loadArticle': 'load' }), // other component specific methods } } </script> UsingVuex Map Vuex actions in the local scope ( mapAction helper & spread operator) Templates stay the same
  • 32. Vuex Menu.vue (update selected item) Content.vue (display the content) Breadcrumbs.vue (display the current node) App.vue (update the <title>) import { mapState } from 'vuex' export default { computed: { ...mapState({ loading: state => state.loading, error: state => state.error, article: state => state.article }) }, watch: { article: (value, previous) { // trigger an update } error: (value) { if (value) { // signal an error to the user } } } }
  • 33. HTML event handlers!?! ● Efficient DOM manipulation with Virtual DOM ● ● lightweight ● efficient DOM manipulation ● separation of concerns & encapsulation ● routing (HTML5 History API & hash sign) ● state management with Vuex
  • 34.
  • 35. $ npm install -g vue-cli $ vue init webpack my-first-vue-project Vue CLI ● Quickly start a new project ● Multiple templates and build systems * ● Sets up linters (AirBNB or Standard) ● Unit tests (karma) ● End to end tests (Nightwatch) * if in doubt, use Webpack
  • 37. Resources ● vuejs.org ● router.vuejs.org ● vuex.vuejs.org ● vuejs/awesome-vue