SlideShare a Scribd company logo
Vue.js
Introduction
Meir Rotstein
www.rotstein.co.il
4.2018
● Created by Evan You - A former Google
employee
● Vue Introduced as “progressive frontend
framework”
● First released on Oct 2015
● Latest release is 2.5.x
Popularity
Vue.js
React
Angular
Let’s dive in
Vue.js is declarative and reactive
<div id="app">
{{ message }}
</div>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
<div id="app-2">
<span v-bind:title="message">
Hover your mouse over me for a few
seconds
to see my dynamically bound title!
</span>
</div>
var app2 = new Vue({
el: '#app-2',
data: {
message: 'You loaded this page on ' +
new Date().toLocaleString()
}
})
The Vue Instance
<div id="app">
{{ message }}
</div>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
● Vue Components is a Vue instance
● Root component must declare the el option, which is the css selector of
the HTML element in the a page that will contain the Vue rendered
artifacts
● The Vue constructor get an options object which contains the component
configuration, some of the main configurations:
○ name
○ data
○ props
○ methods
○ computed
○ el
○ template
○ Lifecycle hooks
○ events
○ watch
○ ...
Lifecycle diagram
The Vue Component
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count
}} times.</button>'
})
<div id="components-demo">
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
</div>
● Components are reusable
Vue instances with a name
● The data option MUST be a
function (otherwise is will
affect ALL the instances of
the component)
● Components are organized in
a tree structure
template and directives
<span>Message: {{ msg }} </span>
<span>Message: {{ message. split('').reverse().join('') }}</span>
<p v-if="seen">Now you see me </p>
<a v-bind:href="url">Click me</a>
<a v-on:click="doSomething">Click me</a>
<form v-on:submit.prevent="onSubmit"></form>
<a :href="url">Click me</a>
<a @click="doSomething">Click me</a>
<a v-mycoolcustomdirective="cooldata">Click me</a>
● Based on the Mustache
syntax
● Common directives:
○ v-if
○ v-for
○ v-show
○ v-once
○ v-html
○ v-bind for data binding
(use : for shorthand)
○ v-on for events (use @
for shorthand)
● You can also implement your
own custom directives
Conditional Rendering
<div v-if="type === 'A'">
A
</div>
<div v-else-if="type === 'B'">
B
</div>
<div v-else-if="type === 'C'">
C
</div>
<div v-else>
Not A/B/C
</div>
<h1 v-show="ok">Hello!</h1>
● Use v-if directive for
conditional rendering
● Use v-else-if and v-else for
if-else logic
● Use v-show directive for
conditional visibility
● v-if will render the element
only if the condition is met,
v-show will render the
element anyway but will
toggle its visibility.
As a thumb rule it is better to
use v-if
Use v-show only for a reason.
e.g. the component state
should be preserved
List Rendering
<ul id="example-1">
<li v-for="item in items">
{{ item.message }}
</li>
</ul>
<div v-for="(value, key, index) in object">
{{ index }}. {{ key }}: {{ value }}
</div>
<ul id="v-for-object" class="demo">
<!--{firstName: 'John',lastName: 'Doe',age: 30}-->
<li v-for="value in object">
{{ value }}
</li>
</ul>
<div v-for="item in items" :key="item.id">
<!-- content -->
</div>
<!-- v-if will run for each v-for integration -->
<li v-for="item in items" v-if="item.exists">
<!-- content -->
</div>
● Use v-for directive for list
rendering
● Syntax is:
v-for="item in items"
Where items is the data
array and item is the
element alias
● As Vue uses the “in-place
patch” strategy it is best to
bind the key attribute with
unique key.
This will allow Vue to
optimize the list rendering
when reacting to data
changes
Starting 2.2.0 it is required for
looping over components
v-for and v-if
Bad:
<!-- v-if will run for each v-for integration -->
<li v-for="item in items" v-if="item.exists">
<!-- content -->
</li>
Good:
<ul v-if="items.length">
<li v-for="item in items">
<!-- content -->
</li>
</ul>
● v-for as higher priority than
v-if, meaning the v-if
calculation will take place for
each item on the list
● Optimize it by wrapping the
entire loop with v-if
Events
<div>
<button v-on:click= "counter += 1" >Add 1</button>
<p>The button above has been clicked {{ counter }} times.</p>
</div>
<div>
<!-- `greet` is the name of a method defined in the component -->
<button v-on:click= "greet">Greet</button>
</div>
<div>
<button @click= "say('hi')" >Say hi</button>
<button @click= "say('what')" >Say what</button>
</div>
<input v-on:keyup.enter= "submit">
this.$emit('myEvent')
<my-component v-on:my-event= "doSomething" ></my-component>
● Use v-on directive to listen to
DOM and custom events
● A listener can be both
method or inline handler
● Vue provides Event Modifiers
for handling a specific variant
of event (for instance: keyup
of the Enter key)
● A component may also emit a
custom event using the
this.$emit method - use the
name of the event in camel
case
● You can use @ as a
shorthand for Events
Data distribution: parent to child
Parent:
new Vue({
el: '#blog-post-demo',
data: {
posts: [
{ id: 1, title: 'My journey with Vue' },
{ id: 2, title: 'Blogging with Vue' },
{ id: 3, title: 'Why Vue is so fun' },
]
}
})
<blog-post
v-for="post in posts"
v-bind:key="post.id"
v-bind:title="post.title">
</blog-post>
● A parent component passes
the data to its child
component using props
● A component should declare
its own props
● props declaration has many
useful capabilities such as
type declaration, validators,
default value etc.
Component:
Vue.component('blog-post', {
props: {
title: {
type: String,
required: true,
}
},
template: '<h3>{{ title }}</h3>'
})
Data distribution: child to parent
Parent:
new Vue({
el: '#blog-post-demo',
data: {
posts: [...],
postFontSize: 1
},
methods: {
onEnlargeText: (enlargeAmount) => {
this.postFontSize += enlargeAmount
}
}
})
<div :style="{ fontSize: postFontSize + 'em' }">
<blog-post
v-for="post in posts"
v-bind:key="post.id"
v-bind:post="post"
v-on:enlarge-text="onEnlargeText">
</blog-post>
</div>
● Sometime we would like the child component to pass data to is parent - for this we will use Events
Component:
Vue.component('blog-post', {
props: {
post: {
type: Object,
required: true,
}
},
template: `
<div class="blog-post">
<h3>{{ post.title }}</h3>
<button
v-on:click="$emit('enlarge-text', 0.1)">
Enlarge text
</button>
<div v-html="post.content"></div>
</div>
`
})
Data distribution: v-model
● v-model is a directive that allows two way data binding for component
● v-model is automatically supported for components that implements the value prop and the input event
Native elements:
<input
v-bind:value="searchText"
v-on:input="searchText =
$event.target.value">
Is the same as:
<input v-model= "searchText" >
Custom elements:
Vue.component('custom-input', {
props: ['value'],
template: `
<input
v-bind:value="value"
v-on:input="$emit('input',
$event.target.value)">
`
})
Usage:
<custom-input v-model="searchText"></custom-input>
Slots
● Slots allows to inject free content into your component (text, html and other components)
Template of <navigation-link> component:
<a
v-bind:href="url"
class="nav-link">
<slot></slot>
</a>
Usage:
<navigation-link url="/profile">
Your Profile
</navigation-link>
<a href="/profile" class="nav-link">
Your Profile
</a>
Usage:
<navigation-link url="/profile">
<!-- Use a component to add an icon -->
<font-awesome-icon name="user"></font-awesome-icon>
Your Profile
</navigation-link>
<a href="/profile" class="nav-link">
<span class="fs fs-user"></span>
Your Profile
</a>
Named Slots
● Allows a component to have multiple slots
Template of <base-layout>
component:
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer">Default
footer</slot>
</footer>
</div>
Usage 1:
<base-layout>
<template slot="header">
<h1>Here might be a page
title</h1>
</template>
<p>A paragraph for the main
content.</p>
<p>And another one.</p>
<template slot="footer">
<p>Here's some contact
info</p>
</template>
</base-layout>
Usage 2:
<base-layout>
<h1 slot="header">Here might
be a page title</h1>
<p>A paragraph for the main
content.</p>
<p>And another one.</p>
<p slot="footer">Here's some
contact info</p>
</base-layout>
Scope of the Slots
As the content of the slot is declared in the parent component - it
inherits the parent scope, for example:
In this example user if declared in the parent component and
navigation-link cannot access it.
But what if you do want to the slot to access the child component
data?
<navigation-link url="/profile" :class="user.class">
Logged in as {{ user.name }}
</navigation-link>
Scoped Slots
● Introduced on v2.1.0
● Scoped Slots allows to define the scope of the slot
Template of <todo-list> component:
<ul>
<li
v-for="todo in todos"
v-bind:key="todo.id">
<!-- passing the todo as slot
prop -->
<slot v-bind:todo="todo">
<!-- Fallback content -->
{{ todo.text }}
</slot>
</li>
</ul>
Usage:
<todo-list v-bind:todos="todos">
<!-- Define `slotProps` as the name of our slot scope -->
<template slot-scope="slotProps">
<!-- Define a custom template for todo items, using -->
<!-- `slotProps` to customize each todo. -->
<span v-if="slotProps.todo.isComplete">✓</span>
{{ slotProps.todo.text }}
</template>
</todo-list>
Dynamic Components
● Sometimes, it’s useful to
dynamically switch between
components
● In this example the content is
changes on the selected tabs
● currentTabComponent prop can
hold either the component name
or object
<!-- Component changes when currentTabComponent changes
-->
<component v-bind:is= "currentTabComponent" ></component>
Computed properties
<div id="example">
{{ message.split('').reverse().join('') }}
</div>
● Instead of using complex logic in the
template - use computed props
● they are considered as read only
properties of the component, therefore
you refer it as property, not as a
function ( no () )
● Computed props are cached - it will not
be re-evaluated if no dependency has
changed (as opposed to methods)
● Although computed props are enough
in most of the use cases, Vue offers
also a watch mechanism for handling
special cases.
<div id="example">
<p>Original message: "{{ message }}"</p>
<p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
var vm = new Vue({
el: '#example',
data: {
message: 'Hello'
},
computed: {
// a computed getter
reversedMessage: function () {
// `this` points to the vm instance
return this.message.split('').reverse().join('')
}
}
})
Reactivity rules
● Vue listen to changes only for properties
that were defined in the data option -
under the hoods it uses
Object.defineProperty for tracking
changes
● You cannot dynamically add properties to
data - declare empty placeholders for
future usage
● Vue cannot identify deep changes on data
- use Vue.set or re-assign the changes
property
var vm = new Vue({
data: {
// declare message with an empty value
message: ''
},
template: '<div>{{ message }}</div>'
})
vm.message = 'Hello!'
vm.message2 = 'Hello!' // not reactive
this.someObject.b = 2 // not recative
// following are recative
this.$set(this.someObject, 'b', 2) // alias of Vue.set
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2
})
Reactivity rules - cont.
● Reactivity changes are taking place on
the next event loop (tick)
Vue.component('example', {
template: '<span>{{ message }}</span>',
data: () => {
return {
message: 'not updated'
}
},
methods: {
updateMessage: () => {
this.message = 'updated'
console.log(this.$el.textContent) // => 'not updated'
this.$nextTick(() => {
console.log(this.$el.textContent) // => 'updated'
})
}
}
})
Single File Components
● *.vue extension
● All the component assets are on the same
file - no jumping between template/js/css
files
● IDE plugins for syntax highlighting
● As the project got bigger it keeps it more
organized and reduce the amount of files
and layers.
Devtools
● VSCode extension: Vetur
● Chrome extension: vujs-devtools
https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en
More info to be found in
https://vuejs.org/

More Related Content

What's hot

Vue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue routerVue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue router
Katy Slemon
 
GWT integration with Vaadin
GWT integration with VaadinGWT integration with Vaadin
GWT integration with Vaadin
Peter Lehto
 
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
Rob Bontekoe
 
Opencast Admin UI - Introduction to developing using AngularJS
Opencast Admin UI - Introduction to developing using AngularJSOpencast Admin UI - Introduction to developing using AngularJS
Opencast Admin UI - Introduction to developing using AngularJS
buttyx
 
WordPress Admin UI - Future Proofing Your Admin Pages
WordPress Admin UI - Future Proofing Your Admin PagesWordPress Admin UI - Future Proofing Your Admin Pages
WordPress Admin UI - Future Proofing Your Admin PagesBrandon Dove
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
TrevorBurnham
 
Using RequireJS with CakePHP
Using RequireJS with CakePHPUsing RequireJS with CakePHP
Using RequireJS with CakePHP
Stephen Young
 
How to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.xHow to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.x
Andolasoft Inc
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
[T]echdencias
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Ivan Chepurnyi
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Igor Bronovskyy
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
GeeksLab Odessa
 
Magento Indexes
Magento IndexesMagento Indexes
Magento Indexes
Ivan Chepurnyi
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
Nir Kaufman
 
Dethroning Grunt: Simple and Effective Builds with gulp.js
Dethroning Grunt: Simple and Effective Builds with gulp.jsDethroning Grunt: Simple and Effective Builds with gulp.js
Dethroning Grunt: Simple and Effective Builds with gulp.js
Jay Harris
 
Optimizing Magento by Preloading Data
Optimizing Magento by Preloading DataOptimizing Magento by Preloading Data
Optimizing Magento by Preloading Data
Ivan Chepurnyi
 
Symfony tips and tricks
Symfony tips and tricksSymfony tips and tricks
Symfony tips and tricks
Javier Eguiluz
 
Overlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MyOverlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh My
Steve McMahon
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
Parashuram N
 
Refactoring Large Web Applications with Backbone.js
Refactoring Large Web Applications with Backbone.jsRefactoring Large Web Applications with Backbone.js
Refactoring Large Web Applications with Backbone.js
Stacy London
 

What's hot (20)

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
 
GWT integration with Vaadin
GWT integration with VaadinGWT integration with Vaadin
GWT integration with Vaadin
 
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
 
Opencast Admin UI - Introduction to developing using AngularJS
Opencast Admin UI - Introduction to developing using AngularJSOpencast Admin UI - Introduction to developing using AngularJS
Opencast Admin UI - Introduction to developing using AngularJS
 
WordPress Admin UI - Future Proofing Your Admin Pages
WordPress Admin UI - Future Proofing Your Admin PagesWordPress Admin UI - Future Proofing Your Admin Pages
WordPress Admin UI - Future Proofing Your Admin Pages
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Using RequireJS with CakePHP
Using RequireJS with CakePHPUsing RequireJS with CakePHP
Using RequireJS with CakePHP
 
How to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.xHow to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.x
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
 
Magento Indexes
Magento IndexesMagento Indexes
Magento Indexes
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
 
Dethroning Grunt: Simple and Effective Builds with gulp.js
Dethroning Grunt: Simple and Effective Builds with gulp.jsDethroning Grunt: Simple and Effective Builds with gulp.js
Dethroning Grunt: Simple and Effective Builds with gulp.js
 
Optimizing Magento by Preloading Data
Optimizing Magento by Preloading DataOptimizing Magento by Preloading Data
Optimizing Magento by Preloading Data
 
Symfony tips and tricks
Symfony tips and tricksSymfony tips and tricks
Symfony tips and tricks
 
Overlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MyOverlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh My
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
 
Refactoring Large Web Applications with Backbone.js
Refactoring Large Web Applications with Backbone.jsRefactoring Large Web Applications with Backbone.js
Refactoring Large Web Applications with Backbone.js
 

Similar to Introduction to Vue.js

Meet VueJs
Meet VueJsMeet VueJs
Meet VueJs
Mathieu Breton
 
Love at first Vue
Love at first VueLove at first Vue
Love at first Vue
Dalibor Gogic
 
The Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.jsThe Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.js
Holly Schinsky
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
TO THE NEW Pvt. Ltd.
 
Basics of VueJS
Basics of VueJSBasics of VueJS
Basics of VueJS
Squash Apps Pvt Ltd
 
Web Components for Java Developers
Web Components for Java DevelopersWeb Components for Java Developers
Web Components for Java Developers
Joonas Lehtinen
 
Developing New Widgets for your Views in Owl
Developing New Widgets for your Views in OwlDeveloping New Widgets for your Views in Owl
Developing New Widgets for your Views in Owl
Odoo
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalystsvilen.ivanov
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
Tudor Barbu
 
Creating GUI container components in Angular and Web Components
Creating GUI container components in Angular and Web ComponentsCreating GUI container components in Angular and Web Components
Creating GUI container components in Angular and Web Components
Rachael L Moore
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
Pagepro
 
Vue js 2.x
Vue js 2.xVue js 2.x
Vue js 2.x
Suresh Velusamy
 
Level up apps and websites with vue.js
Level up  apps and websites with vue.jsLevel up  apps and websites with vue.js
Level up apps and websites with vue.js
Violetta Villani
 
Level up apps and websites with vue.js
Level up  apps and websites with vue.jsLevel up  apps and websites with vue.js
Level up apps and websites with vue.js
Commit University
 
Vue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentówVue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentów
Laravel Poland MeetUp
 
Nuxtjs cheat-sheet
Nuxtjs cheat-sheetNuxtjs cheat-sheet
Nuxtjs cheat-sheet
ValeriaCastillo71
 
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...Alessandro Nadalin
 
Webinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST APIWebinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST API
WP Engine
 
Webinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST APIWebinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST API
WP Engine UK
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2
Paras Mendiratta
 

Similar to Introduction to Vue.js (20)

Meet VueJs
Meet VueJsMeet VueJs
Meet VueJs
 
Love at first Vue
Love at first VueLove at first Vue
Love at first Vue
 
The Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.jsThe Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.js
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Basics of VueJS
Basics of VueJSBasics of VueJS
Basics of VueJS
 
Web Components for Java Developers
Web Components for Java DevelopersWeb Components for Java Developers
Web Components for Java Developers
 
Developing New Widgets for your Views in Owl
Developing New Widgets for your Views in OwlDeveloping New Widgets for your Views in Owl
Developing New Widgets for your Views in Owl
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
 
Creating GUI container components in Angular and Web Components
Creating GUI container components in Angular and Web ComponentsCreating GUI container components in Angular and Web Components
Creating GUI container components in Angular and Web Components
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Vue js 2.x
Vue js 2.xVue js 2.x
Vue js 2.x
 
Level up apps and websites with vue.js
Level up  apps and websites with vue.jsLevel up  apps and websites with vue.js
Level up apps and websites with vue.js
 
Level up apps and websites with vue.js
Level up  apps and websites with vue.jsLevel up  apps and websites with vue.js
Level up apps and websites with vue.js
 
Vue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentówVue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentów
 
Nuxtjs cheat-sheet
Nuxtjs cheat-sheetNuxtjs cheat-sheet
Nuxtjs cheat-sheet
 
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
 
Webinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST APIWebinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST API
 
Webinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST APIWebinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST API
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2
 

Recently uploaded

LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 

Recently uploaded (20)

LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 

Introduction to Vue.js

  • 2. ● Created by Evan You - A former Google employee ● Vue Introduced as “progressive frontend framework” ● First released on Oct 2015 ● Latest release is 2.5.x
  • 5. Vue.js is declarative and reactive <div id="app"> {{ message }} </div> var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } }) <div id="app-2"> <span v-bind:title="message"> Hover your mouse over me for a few seconds to see my dynamically bound title! </span> </div> var app2 = new Vue({ el: '#app-2', data: { message: 'You loaded this page on ' + new Date().toLocaleString() } })
  • 6. The Vue Instance <div id="app"> {{ message }} </div> var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } }) ● Vue Components is a Vue instance ● Root component must declare the el option, which is the css selector of the HTML element in the a page that will contain the Vue rendered artifacts ● The Vue constructor get an options object which contains the component configuration, some of the main configurations: ○ name ○ data ○ props ○ methods ○ computed ○ el ○ template ○ Lifecycle hooks ○ events ○ watch ○ ...
  • 8. The Vue Component Vue.component('button-counter', { data: function () { return { count: 0 } }, template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>' }) <div id="components-demo"> <button-counter></button-counter> <button-counter></button-counter> <button-counter></button-counter> </div> ● Components are reusable Vue instances with a name ● The data option MUST be a function (otherwise is will affect ALL the instances of the component) ● Components are organized in a tree structure
  • 9. template and directives <span>Message: {{ msg }} </span> <span>Message: {{ message. split('').reverse().join('') }}</span> <p v-if="seen">Now you see me </p> <a v-bind:href="url">Click me</a> <a v-on:click="doSomething">Click me</a> <form v-on:submit.prevent="onSubmit"></form> <a :href="url">Click me</a> <a @click="doSomething">Click me</a> <a v-mycoolcustomdirective="cooldata">Click me</a> ● Based on the Mustache syntax ● Common directives: ○ v-if ○ v-for ○ v-show ○ v-once ○ v-html ○ v-bind for data binding (use : for shorthand) ○ v-on for events (use @ for shorthand) ● You can also implement your own custom directives
  • 10. Conditional Rendering <div v-if="type === 'A'"> A </div> <div v-else-if="type === 'B'"> B </div> <div v-else-if="type === 'C'"> C </div> <div v-else> Not A/B/C </div> <h1 v-show="ok">Hello!</h1> ● Use v-if directive for conditional rendering ● Use v-else-if and v-else for if-else logic ● Use v-show directive for conditional visibility ● v-if will render the element only if the condition is met, v-show will render the element anyway but will toggle its visibility. As a thumb rule it is better to use v-if Use v-show only for a reason. e.g. the component state should be preserved
  • 11. List Rendering <ul id="example-1"> <li v-for="item in items"> {{ item.message }} </li> </ul> <div v-for="(value, key, index) in object"> {{ index }}. {{ key }}: {{ value }} </div> <ul id="v-for-object" class="demo"> <!--{firstName: 'John',lastName: 'Doe',age: 30}--> <li v-for="value in object"> {{ value }} </li> </ul> <div v-for="item in items" :key="item.id"> <!-- content --> </div> <!-- v-if will run for each v-for integration --> <li v-for="item in items" v-if="item.exists"> <!-- content --> </div> ● Use v-for directive for list rendering ● Syntax is: v-for="item in items" Where items is the data array and item is the element alias ● As Vue uses the “in-place patch” strategy it is best to bind the key attribute with unique key. This will allow Vue to optimize the list rendering when reacting to data changes Starting 2.2.0 it is required for looping over components
  • 12. v-for and v-if Bad: <!-- v-if will run for each v-for integration --> <li v-for="item in items" v-if="item.exists"> <!-- content --> </li> Good: <ul v-if="items.length"> <li v-for="item in items"> <!-- content --> </li> </ul> ● v-for as higher priority than v-if, meaning the v-if calculation will take place for each item on the list ● Optimize it by wrapping the entire loop with v-if
  • 13. Events <div> <button v-on:click= "counter += 1" >Add 1</button> <p>The button above has been clicked {{ counter }} times.</p> </div> <div> <!-- `greet` is the name of a method defined in the component --> <button v-on:click= "greet">Greet</button> </div> <div> <button @click= "say('hi')" >Say hi</button> <button @click= "say('what')" >Say what</button> </div> <input v-on:keyup.enter= "submit"> this.$emit('myEvent') <my-component v-on:my-event= "doSomething" ></my-component> ● Use v-on directive to listen to DOM and custom events ● A listener can be both method or inline handler ● Vue provides Event Modifiers for handling a specific variant of event (for instance: keyup of the Enter key) ● A component may also emit a custom event using the this.$emit method - use the name of the event in camel case ● You can use @ as a shorthand for Events
  • 14. Data distribution: parent to child Parent: new Vue({ el: '#blog-post-demo', data: { posts: [ { id: 1, title: 'My journey with Vue' }, { id: 2, title: 'Blogging with Vue' }, { id: 3, title: 'Why Vue is so fun' }, ] } }) <blog-post v-for="post in posts" v-bind:key="post.id" v-bind:title="post.title"> </blog-post> ● A parent component passes the data to its child component using props ● A component should declare its own props ● props declaration has many useful capabilities such as type declaration, validators, default value etc. Component: Vue.component('blog-post', { props: { title: { type: String, required: true, } }, template: '<h3>{{ title }}</h3>' })
  • 15. Data distribution: child to parent Parent: new Vue({ el: '#blog-post-demo', data: { posts: [...], postFontSize: 1 }, methods: { onEnlargeText: (enlargeAmount) => { this.postFontSize += enlargeAmount } } }) <div :style="{ fontSize: postFontSize + 'em' }"> <blog-post v-for="post in posts" v-bind:key="post.id" v-bind:post="post" v-on:enlarge-text="onEnlargeText"> </blog-post> </div> ● Sometime we would like the child component to pass data to is parent - for this we will use Events Component: Vue.component('blog-post', { props: { post: { type: Object, required: true, } }, template: ` <div class="blog-post"> <h3>{{ post.title }}</h3> <button v-on:click="$emit('enlarge-text', 0.1)"> Enlarge text </button> <div v-html="post.content"></div> </div> ` })
  • 16. Data distribution: v-model ● v-model is a directive that allows two way data binding for component ● v-model is automatically supported for components that implements the value prop and the input event Native elements: <input v-bind:value="searchText" v-on:input="searchText = $event.target.value"> Is the same as: <input v-model= "searchText" > Custom elements: Vue.component('custom-input', { props: ['value'], template: ` <input v-bind:value="value" v-on:input="$emit('input', $event.target.value)"> ` }) Usage: <custom-input v-model="searchText"></custom-input>
  • 17. Slots ● Slots allows to inject free content into your component (text, html and other components) Template of <navigation-link> component: <a v-bind:href="url" class="nav-link"> <slot></slot> </a> Usage: <navigation-link url="/profile"> Your Profile </navigation-link> <a href="/profile" class="nav-link"> Your Profile </a> Usage: <navigation-link url="/profile"> <!-- Use a component to add an icon --> <font-awesome-icon name="user"></font-awesome-icon> Your Profile </navigation-link> <a href="/profile" class="nav-link"> <span class="fs fs-user"></span> Your Profile </a>
  • 18. Named Slots ● Allows a component to have multiple slots Template of <base-layout> component: <div class="container"> <header> <slot name="header"></slot> </header> <main> <slot></slot> </main> <footer> <slot name="footer">Default footer</slot> </footer> </div> Usage 1: <base-layout> <template slot="header"> <h1>Here might be a page title</h1> </template> <p>A paragraph for the main content.</p> <p>And another one.</p> <template slot="footer"> <p>Here's some contact info</p> </template> </base-layout> Usage 2: <base-layout> <h1 slot="header">Here might be a page title</h1> <p>A paragraph for the main content.</p> <p>And another one.</p> <p slot="footer">Here's some contact info</p> </base-layout>
  • 19. Scope of the Slots As the content of the slot is declared in the parent component - it inherits the parent scope, for example: In this example user if declared in the parent component and navigation-link cannot access it. But what if you do want to the slot to access the child component data? <navigation-link url="/profile" :class="user.class"> Logged in as {{ user.name }} </navigation-link>
  • 20. Scoped Slots ● Introduced on v2.1.0 ● Scoped Slots allows to define the scope of the slot Template of <todo-list> component: <ul> <li v-for="todo in todos" v-bind:key="todo.id"> <!-- passing the todo as slot prop --> <slot v-bind:todo="todo"> <!-- Fallback content --> {{ todo.text }} </slot> </li> </ul> Usage: <todo-list v-bind:todos="todos"> <!-- Define `slotProps` as the name of our slot scope --> <template slot-scope="slotProps"> <!-- Define a custom template for todo items, using --> <!-- `slotProps` to customize each todo. --> <span v-if="slotProps.todo.isComplete">✓</span> {{ slotProps.todo.text }} </template> </todo-list>
  • 21. Dynamic Components ● Sometimes, it’s useful to dynamically switch between components ● In this example the content is changes on the selected tabs ● currentTabComponent prop can hold either the component name or object <!-- Component changes when currentTabComponent changes --> <component v-bind:is= "currentTabComponent" ></component>
  • 22. Computed properties <div id="example"> {{ message.split('').reverse().join('') }} </div> ● Instead of using complex logic in the template - use computed props ● they are considered as read only properties of the component, therefore you refer it as property, not as a function ( no () ) ● Computed props are cached - it will not be re-evaluated if no dependency has changed (as opposed to methods) ● Although computed props are enough in most of the use cases, Vue offers also a watch mechanism for handling special cases. <div id="example"> <p>Original message: "{{ message }}"</p> <p>Computed reversed message: "{{ reversedMessage }}"</p> </div> var vm = new Vue({ el: '#example', data: { message: 'Hello' }, computed: { // a computed getter reversedMessage: function () { // `this` points to the vm instance return this.message.split('').reverse().join('') } } })
  • 23. Reactivity rules ● Vue listen to changes only for properties that were defined in the data option - under the hoods it uses Object.defineProperty for tracking changes ● You cannot dynamically add properties to data - declare empty placeholders for future usage ● Vue cannot identify deep changes on data - use Vue.set or re-assign the changes property var vm = new Vue({ data: { // declare message with an empty value message: '' }, template: '<div>{{ message }}</div>' }) vm.message = 'Hello!' vm.message2 = 'Hello!' // not reactive this.someObject.b = 2 // not recative // following are recative this.$set(this.someObject, 'b', 2) // alias of Vue.set this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })
  • 24. Reactivity rules - cont. ● Reactivity changes are taking place on the next event loop (tick) Vue.component('example', { template: '<span>{{ message }}</span>', data: () => { return { message: 'not updated' } }, methods: { updateMessage: () => { this.message = 'updated' console.log(this.$el.textContent) // => 'not updated' this.$nextTick(() => { console.log(this.$el.textContent) // => 'updated' }) } } })
  • 25. Single File Components ● *.vue extension ● All the component assets are on the same file - no jumping between template/js/css files ● IDE plugins for syntax highlighting ● As the project got bigger it keeps it more organized and reduce the amount of files and layers.
  • 26. Devtools ● VSCode extension: Vetur ● Chrome extension: vujs-devtools https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en
  • 27. More info to be found in https://vuejs.org/