SlideShare une entreprise Scribd logo
1  sur  37
Télécharger pour lire hors ligne
Love at first Vue
* Vue (pronounced /vjuː/, like view)
*
So What’s Vue.js?
SO WHAT’S VUE.JS
It's a Open-source progressive framework for building user interfaces.
Its focused on the view layer only.
It has a Virtual DOM and composable, reactive components.
Its core is small and works well with companion libraries for routing, global state, and HTTP requests.
It's light, fast, and flexible.
First release Feb. 2014
2.0 release (stable) in Oct. 2016
~45.9k stars on Github
~ 410,497 downloads in the last month (npm only)
Small learning curve and semantic
Pre-processor agnostic (Jade/Pug, Scss, Stylus)
Server Side Rendering
Stable, maintaned and tested
Single File Vue Components
● Imported as ES6 module.
● Collocation of Template, Logic and Style.
● Use what you already know:
HTML, CSS and JavaScript.
● Component-scoped CSS
(no conflicts)
<template lang="pug">
.my-component
h1 {{ msg }}
other-component
</template>
<script>
import OtherComponent from './OtherComponent.vue'
export default {
components: { OtherComponent },
data () {
return {
msg: 'Hello Vue.js'
}
}
}
</script>
<style lang="stylus" scoped>
font-stack = Helvetica, sans-serif
primary-color = #333
.my-component
color primary-color
font-family font-stack
</style>
Ecosystem
ECOSYSTEM
vuex (state management)
vue-resource (HTTP requests)
vue-router (routing)
vue-cli (command line scaffolding)
vue-devtools (chrome devtools extension for debugging)
awesome-vue (list of awesome things related to Vue.js)
Getting Started
GETTING STARTED
The easiest way to try out Vue.js is using the Codepen example.
Feel free to fork it and follow along as we go through some basic examples.
Or, you can simply create an .html file and include Vue with:
<script src="//unpkg.com/vue"></script>
Getting started
Vue-cli
A simple CLI for scaffolding Vue.js projects.
$ npm i -g vue-cli # Install vue-cli if you haven't already
$ vue init daliborgogic/vue-simple-boilerplate # Create a new project based on this template
$ cd vue-simple-boilerplate # Navigate into your new project folder
$ npm i -g live-server # Install live-server if you haven't already
$ live-server # Run live-server and open it in your browser
Fork It And Make Your Own
You can fork this repo to create your own boilerplate, and use it with vue-cli:
$ vue init username/repo my-project
Getting started
Declarative Rendering
HTML
<div id="app">
{{ message }}
</div>
JS
new Vue({
el: '#app',
data: {
message: 'Welcome!'
}
})
Getting started
Binding
HTML
<div id="app">
<span v-bind:title="message">
Hover your mouse over me for a few seconds to see my dynamically bound title!
</span>
</div>
JS
new Vue({
el: '#app',
data: {
message: 'You loaded this page on ' + new Date()
}
})
The v-bind attribute is called a directive.
Directives are prefixed with v-.
They apply special reactive behavior to the rendered DOM.
Getting started
Conditionals
HTML
<div id="app">
<p v-if="seen">Now you see me</p>
</div>
JS
new Vue({
el: '#app',
data: {
seen: true
}
})
We can bind data to not only text and attributes, but also the structure of the DOM.
Getting started
Loops
HTML
<div id="app">
<ol>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ol>
</div>
JS
new Vue({
el: '#app',
data: {
todos: [
{ text: 'Learn JavaScript' },
{ text: 'Learn Vue' },
{ text: 'Build something awesome' }
]
}
})
Getting started
Handling User Input
To let users interact with your app, we can use the
v-on directive to attach event listeners that invoke
methods on our Vue instances:
Note in the method we simply update the state of
our app without touching the DOM - all DOM
manipulations are handled by Vue.
HTML
<div id="app">
<p>{{ message }}</p>
<button v-on:click="reverseMessage">Reverse Message</button>
</div>
JS
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
},
methods: {
reverseMessage: function () {
this.message = this.message.split('').reverse().join('')
}
}
})
Getting started
Two-way binding
HTML
<div id="app">
<p>{{ message }}</p>
<input v-model="message">
</div>
JS
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
}
})
Getting started
Components
allows us to build large-scale applications composed of small,
Self-contained and often reusable components.
A component is essentially a Vue instance with pre-defined options.
Registering a component in Vue is straightforward:
JS
Vue.component('todo-item', {
template: '<li>This is a todo</li>'
})
Now you can compose it in another component’s template:
HTML
<ol>
<todo-item></todo-item>
</ol>
Getting started
But this would render the same text for every todo.
We should be able to pass data from the parent scope into child components.
Let’s modify the component definition to make it accept a prop:
JS
Vue.component('todo-item', {
props: ['todo'],
template: '<li>{{ todo.text }}</li>'
})
Getting started
Now we can pass the todo into each repeated component using v-bind:
HTML
<div id="app">
<ol>
<todo-item v-for="item in groceryList" v-bind:todo="item"></todo-item>
</ol>
</div>
JS
Vue.component('todo-item', {
props: ['todo'],
template: '<li>{{ todo.text }}</li>'
})
new Vue({
el: '#app',
data: {
groceryList: [
{ text: 'Vegetables' },
{ text: 'Cheese' },
{ text: 'Whatever else humans are supposed to eat' }
]
}
})
Getting started
TODO list example
HTML
<div id="todo">
<input type="text" placeholder="Add new task" @keyup.enter="addItem"/>
<ul>
<li v-for="item in items">
<span :class="{'done': item.done}">{{item.text}}</span>
<button @click="toggleItem(item)">{{item.done ? 'Not done': 'Done'}}</button>
<button @click="deleteItem(item)">Delete</button>
</li>
</ul>
</div>
JS
new Vue ({
el: '#todo',
data: {
items: []
},
methods: {
addItem (e) {
this.items.push({
text: e.target.value,
done: false
})
e.target.value = ''
},
toggleItem (item) {
item.done = !item.done
},
deleteItem (item) {
this.items.splice(this.items.indexOf(item), 1)
}
}
})
CSS
.done {
text-decoration: line-thorough;
}
Routing
Single Page Application (SPA)
1. Entire app loaded on a single page
2. No page reload on UI navigation
3. Dynamically update UI with ajax-fetched data
Dynamic page-level component
// routes templates
const NotFound = {template: '<p>404</p>'}
const Home = {template: '<p>Home page</p>'}
const About = {template: '<p>About page</p>'}
// routes mapping
let routes = {
'/': Home,
'/about': About
}
// vue instance
new Vue({
el: '#app',
data: {
currentRoute: window.location.pathname
},
computed: {
ViewComponent () {
return routes[this.currentRoute] || Notound
}
},
render (h) {
return h(this.ViewComponent)
}
})
Vue Router
1. Dynamic route matching (patterns)
2. HTML5 history API (states)
3. Lazy-loading (async components)
4. Nested routes
5. Navigation guards (authentication, preloading...)
Vue CLI
The simplest possible Vue setup in a single HTML file
$ npm i -g vue-cli # Install vue-cli if you haven't already
$ vue init simple # Create a new project based on this template
$ cd simple # Navigate into your new project folder
$ npm i -g live-server # Install live-server if you haven't already
$ live-server # Run live-server and open it in your browser
Current available templates include:
webpack - A full-featured Webpack + vue-loader setup with hot reload, linting, testing & css extraction.
webpack-simple - A simple Webpack + vue-loader setup for quick prototyping.
browserify - A full-featured Browserify + vueify setup with hot-reload, linting & unit testing.
browserify-simple - A simple Browserify + vueify setup for quick prototyping.
simple - Vue setup in a single HTML file
VUE CLI
Vue router and preloading example
$ npm i -g vue-cli
$ vue init webpack-simple app
$ cd app
$ npm i
$ npm run dev
app
/node_modules
/src
/assets
Logo.png
App.vue
Main.js
.babelrc
index.html
package.json
README.md
webpack.config.js
Webpack simple
$ npm i vue-router -S
App.vue
<template lang="pug">
#app
//- caches the inactive component instances withouth destroying them
keep-alive
//- render current route template
router-view
</template>
<script>
export default {
name: 'app'
}
</script>
main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
Vue.use(VueRouter)
const Home = resolve => require(['./views/Home.vue'], resolve)
const About = resolve => require(['./views/About.vue'], resolve)
const NotFound = resolve => require(['./views/NotFound.vue'], resolve)
const router = new VueRouter({
mode: 'history',
routes: [
{path: '/', component: Home},
{path: '/about/:name?', component: About},
{path: '*', component: NotFound}
]
})
const app = new Vue({
el: '#app',
router,
render: h => h(App)
})
Router mode
● Hash - uses the URL hash for routing (hashbang urls /#!/)
● History - uses HTML5 History API (semantic urls)
● Abstract - servre-side with Node.js (all javascript environments)
Server config - nginx
location / {
try_files $uri $uri/ index.html
}
Lazy Loading Routes
Async components to only load them when the route is visited:
const Foo = resolve => require([‘./Foo.vue’], resolve)
const Foo = () => System.import(‘./Foo.vue’)
Built-in Component
Caches inactive components withouth destroy them:
<keep-alive></keep-alive>
$ npm i vuex -S
$ npm i vuex-router-sync@next -S
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
isPreloading: false
}
const mutations = {
beginPreload (state) {
state.isPreloading = true
},
endPreload (state) {
state.isPreloading = false
}
}
const actions = {
beginPreload: ({commit}) => commit('beginPreload'),
endPreload: ({commit}) => commit('endPreload')
}
const getters = {
isPreloading: state => state.isPreloading
}
export default new Vuex.Store({
state,
getters,
actions,
mutations
})
preloader.vue
<template lang="pug">
.preloader(:class="{'hidden': !this.$store.getters.isPreloading}") Loading...
</template>
<style scoped>
.preloader {
...
opacity: 1;
visibility: visible;
}
.preloader.hidden {
opacity: 0;
visibility: hidden;
}
</style>
App.vue
<template lang="pug">
#app
navigation
preloader
keep-alive
router-view
</template>
<script>
import Navigation from './partials/Nav.vue'
import Preloader from './partials/Preloader.vue'
export default {
name: 'app',
components: {Navigation, Preloader}
}
</script>
main.js
...
import store from './store'
import {sync} from 'vuex-router-sync'
const router = new VueRouter({
...
{
path: '/about/:name?',
component: About,
meta: {
preload: true
}
}
...
})
router.beforeEach((to, from, next) => {
if (to.matched.some(m => m.meta.preload)) {
store.dispatch('beginPreload')
next()
} else {
store.dispatch('endPreload')
next()
}
})
sync(store, router)
const app = new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
Navigation Guards
Guard navigations either by redirecting it or canceling it:
globally / per-route / in-component
router.beforeEach((to, from, next) => {})
router.afterEach((to, from, next) => {})
● to: Route : the target Route Object being navigated to.
● from: Route : the current route being navigated away from.
● next: Function : this function must be called to resolve the hook.
Route Meta Fields
Attach abstract information to each route:
● Authentication
● Preloading
● Authorized Referrer
meta: { requiresAuth: true }
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!auth.loggedIn()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next() // make sure to always call next()
}
})
About.vue
<template lang="pug">
div
h1 About {{name}}
</template>
<script>
export default {
name: 'about',
computed: {
name () {
return this.$route.params.name || 'anonymous'
}
},
activated () {
setTimeout(() => {
this.$nextTick(() => {
this.$store.dispatch('endPreload')
})
}, 3000)
}
}
</script>
Github:
https://github.com/daliborgogic/vue-routing-preloading
Thanks!

Contenu connexe

Tendances

State manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to VuexState manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to VuexCommit University
 
An Introduction to Vuejs
An Introduction to VuejsAn Introduction to Vuejs
An Introduction to VuejsPaddy Lock
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.jsPagepro
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVCIndicThreads
 
Intro to vue.js
Intro to vue.jsIntro to vue.js
Intro to vue.jsTechMagic
 
Technologies sur angular.pptx
Technologies sur angular.pptxTechnologies sur angular.pptx
Technologies sur angular.pptxIdrissaDembl
 
Présentation de ECMAScript 6
Présentation de ECMAScript 6Présentation de ECMAScript 6
Présentation de ECMAScript 6Julien CROUZET
 
Basics of Vue.js 2019
Basics of Vue.js 2019Basics of Vue.js 2019
Basics of Vue.js 2019Paul Bele
 

Tendances (20)

State manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to VuexState manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to Vuex
 
An Introduction to Vuejs
An Introduction to VuejsAn Introduction to Vuejs
An Introduction to Vuejs
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Vue js for beginner
Vue js for beginner Vue js for beginner
Vue js for beginner
 
Vue, vue router, vuex
Vue, vue router, vuexVue, vue router, vuex
Vue, vue router, vuex
 
Support cours angular
Support cours angularSupport cours angular
Support cours angular
 
React workshop
React workshopReact workshop
React workshop
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Introduction à Angular
Introduction à AngularIntroduction à Angular
Introduction à Angular
 
Intro to vue.js
Intro to vue.jsIntro to vue.js
Intro to vue.js
 
Spring Boot RestApi.pptx
Spring Boot RestApi.pptxSpring Boot RestApi.pptx
Spring Boot RestApi.pptx
 
Vue Vuex 101
Vue Vuex 101Vue Vuex 101
Vue Vuex 101
 
Basics of VueJS
Basics of VueJSBasics of VueJS
Basics of VueJS
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
React Native
React NativeReact Native
React Native
 
Technologies sur angular.pptx
Technologies sur angular.pptxTechnologies sur angular.pptx
Technologies sur angular.pptx
 
Présentation de ECMAScript 6
Présentation de ECMAScript 6Présentation de ECMAScript 6
Présentation de ECMAScript 6
 
Basics of Vue.js 2019
Basics of Vue.js 2019Basics of Vue.js 2019
Basics of Vue.js 2019
 

Similaire à 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.jsHolly Schinsky
 
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...Codemotion
 
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...Luciano Mammino
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoJavier Abadía
 
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
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoasZeid Hassan
 
How to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScriptHow to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScriptKaty Slemon
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applicationsAstrails
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!David Gibbons
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsMatteo Manchi
 
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
 
Using Renderless Components in Vue.js during your software development.
Using Renderless Components in Vue.js during your software development.Using Renderless Components in Vue.js during your software development.
Using Renderless Components in Vue.js during your software development.tothepointIT
 

Similaire à Love at first Vue (20)

Meet VueJs
Meet VueJsMeet VueJs
Meet VueJs
 
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
 
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
 
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
 
Vue.js part1
Vue.js part1Vue.js part1
Vue.js part1
 
Nuxtjs cheat-sheet
Nuxtjs cheat-sheetNuxtjs cheat-sheet
Nuxtjs cheat-sheet
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
 
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
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoas
 
How to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScriptHow to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScript
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applications
 
Nodejs.meetup
Nodejs.meetupNodejs.meetup
Nodejs.meetup
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!
 
Service workers
Service workersService workers
Service workers
 
Nuxt.js - Introduction
Nuxt.js - IntroductionNuxt.js - Introduction
Nuxt.js - Introduction
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
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)
 
Using Renderless Components in Vue.js during your software development.
Using Renderless Components in Vue.js during your software development.Using Renderless Components in Vue.js during your software development.
Using Renderless Components in Vue.js during your software development.
 
Nuxt Talk
Nuxt TalkNuxt Talk
Nuxt Talk
 

Plus de Dalibor Gogic

#4 HTML & CSS [know-how]
#4 HTML & CSS [know-how]#4 HTML & CSS [know-how]
#4 HTML & CSS [know-how]Dalibor Gogic
 
#3 HTML & CSS [know-how]
#3 HTML & CSS [know-how]#3 HTML & CSS [know-how]
#3 HTML & CSS [know-how]Dalibor Gogic
 
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With YouDalibor Gogic
 
Automatizacija u Front-end razvojnom procesu
Automatizacija u Front-end razvojnom procesuAutomatizacija u Front-end razvojnom procesu
Automatizacija u Front-end razvojnom procesuDalibor Gogic
 

Plus de Dalibor Gogic (6)

#4 HTML & CSS [know-how]
#4 HTML & CSS [know-how]#4 HTML & CSS [know-how]
#4 HTML & CSS [know-how]
 
#3 HTML & CSS [know-how]
#3 HTML & CSS [know-how]#3 HTML & CSS [know-how]
#3 HTML & CSS [know-how]
 
#2 Html [know-how]
#2 Html [know-how]#2 Html [know-how]
#2 Html [know-how]
 
#1 HTML [know-how]
#1 HTML [know-how]#1 HTML [know-how]
#1 HTML [know-how]
 
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With You
 
Automatizacija u Front-end razvojnom procesu
Automatizacija u Front-end razvojnom procesuAutomatizacija u Front-end razvojnom procesu
Automatizacija u Front-end razvojnom procesu
 

Dernier

lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.lodhisaajjda
 
Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Vipesco
 
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...Delhi Call girls
 
Dreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio IIIDreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio IIINhPhngng3
 
Dreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video TreatmentDreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video Treatmentnswingard
 
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...amilabibi1
 
Digital collaboration with Microsoft 365 as extension of Drupal
Digital collaboration with Microsoft 365 as extension of DrupalDigital collaboration with Microsoft 365 as extension of Drupal
Digital collaboration with Microsoft 365 as extension of DrupalFabian de Rijk
 
My Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle BaileyMy Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle Baileyhlharris
 
Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...
Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...
Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...Pooja Nehwal
 
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdfThe workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdfSenaatti-kiinteistöt
 
If this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaIf this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaKayode Fayemi
 
Causes of poverty in France presentation.pptx
Causes of poverty in France presentation.pptxCauses of poverty in France presentation.pptx
Causes of poverty in France presentation.pptxCamilleBoulbin1
 
Report Writing Webinar Training
Report Writing Webinar TrainingReport Writing Webinar Training
Report Writing Webinar TrainingKylaCullinane
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxraffaeleoman
 
Uncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac FolorunsoUncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac FolorunsoKayode Fayemi
 
Sector 62, Noida Call girls :8448380779 Noida Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Noida Escorts | 100% verifiedSector 62, Noida Call girls :8448380779 Noida Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Noida Escorts | 100% verifiedDelhi Call girls
 
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdfAWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdfSkillCertProExams
 

Dernier (18)

lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.
 
Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510
 
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
Busty Desi⚡Call Girls in Sector 51 Noida Escorts >༒8448380779 Escort Service-...
 
Dreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio IIIDreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio III
 
Dreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video TreatmentDreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video Treatment
 
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
Bring back lost lover in USA, Canada ,Uk ,Australia ,London Lost Love Spell C...
 
ICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdfICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdf
 
Digital collaboration with Microsoft 365 as extension of Drupal
Digital collaboration with Microsoft 365 as extension of DrupalDigital collaboration with Microsoft 365 as extension of Drupal
Digital collaboration with Microsoft 365 as extension of Drupal
 
My Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle BaileyMy Presentation "In Your Hands" by Halle Bailey
My Presentation "In Your Hands" by Halle Bailey
 
Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...
Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...
Aesthetic Colaba Mumbai Cst Call girls 📞 7738631006 Grant road Call Girls ❤️-...
 
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdfThe workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
 
If this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaIf this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New Nigeria
 
Causes of poverty in France presentation.pptx
Causes of poverty in France presentation.pptxCauses of poverty in France presentation.pptx
Causes of poverty in France presentation.pptx
 
Report Writing Webinar Training
Report Writing Webinar TrainingReport Writing Webinar Training
Report Writing Webinar Training
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
 
Uncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac FolorunsoUncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac Folorunso
 
Sector 62, Noida Call girls :8448380779 Noida Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Noida Escorts | 100% verifiedSector 62, Noida Call girls :8448380779 Noida Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Noida Escorts | 100% verified
 
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdfAWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
 

Love at first Vue

  • 1. Love at first Vue * Vue (pronounced /vjuː/, like view) *
  • 3. SO WHAT’S VUE.JS It's a Open-source progressive framework for building user interfaces. Its focused on the view layer only. It has a Virtual DOM and composable, reactive components. Its core is small and works well with companion libraries for routing, global state, and HTTP requests. It's light, fast, and flexible. First release Feb. 2014 2.0 release (stable) in Oct. 2016 ~45.9k stars on Github ~ 410,497 downloads in the last month (npm only)
  • 4. Small learning curve and semantic Pre-processor agnostic (Jade/Pug, Scss, Stylus) Server Side Rendering Stable, maintaned and tested
  • 5. Single File Vue Components ● Imported as ES6 module. ● Collocation of Template, Logic and Style. ● Use what you already know: HTML, CSS and JavaScript. ● Component-scoped CSS (no conflicts) <template lang="pug"> .my-component h1 {{ msg }} other-component </template> <script> import OtherComponent from './OtherComponent.vue' export default { components: { OtherComponent }, data () { return { msg: 'Hello Vue.js' } } } </script> <style lang="stylus" scoped> font-stack = Helvetica, sans-serif primary-color = #333 .my-component color primary-color font-family font-stack </style>
  • 7. ECOSYSTEM vuex (state management) vue-resource (HTTP requests) vue-router (routing) vue-cli (command line scaffolding) vue-devtools (chrome devtools extension for debugging) awesome-vue (list of awesome things related to Vue.js)
  • 9. GETTING STARTED The easiest way to try out Vue.js is using the Codepen example. Feel free to fork it and follow along as we go through some basic examples. Or, you can simply create an .html file and include Vue with: <script src="//unpkg.com/vue"></script>
  • 10. Getting started Vue-cli A simple CLI for scaffolding Vue.js projects. $ npm i -g vue-cli # Install vue-cli if you haven't already $ vue init daliborgogic/vue-simple-boilerplate # Create a new project based on this template $ cd vue-simple-boilerplate # Navigate into your new project folder $ npm i -g live-server # Install live-server if you haven't already $ live-server # Run live-server and open it in your browser Fork It And Make Your Own You can fork this repo to create your own boilerplate, and use it with vue-cli: $ vue init username/repo my-project
  • 11. Getting started Declarative Rendering HTML <div id="app"> {{ message }} </div> JS new Vue({ el: '#app', data: { message: 'Welcome!' } })
  • 12. Getting started Binding HTML <div id="app"> <span v-bind:title="message"> Hover your mouse over me for a few seconds to see my dynamically bound title! </span> </div> JS new Vue({ el: '#app', data: { message: 'You loaded this page on ' + new Date() } }) The v-bind attribute is called a directive. Directives are prefixed with v-. They apply special reactive behavior to the rendered DOM.
  • 13. Getting started Conditionals HTML <div id="app"> <p v-if="seen">Now you see me</p> </div> JS new Vue({ el: '#app', data: { seen: true } }) We can bind data to not only text and attributes, but also the structure of the DOM.
  • 14. Getting started Loops HTML <div id="app"> <ol> <li v-for="todo in todos"> {{ todo.text }} </li> </ol> </div> JS new Vue({ el: '#app', data: { todos: [ { text: 'Learn JavaScript' }, { text: 'Learn Vue' }, { text: 'Build something awesome' } ] } })
  • 15. Getting started Handling User Input To let users interact with your app, we can use the v-on directive to attach event listeners that invoke methods on our Vue instances: Note in the method we simply update the state of our app without touching the DOM - all DOM manipulations are handled by Vue. HTML <div id="app"> <p>{{ message }}</p> <button v-on:click="reverseMessage">Reverse Message</button> </div> JS new Vue({ el: '#app', data: { message: 'Hello Vue.js!' }, methods: { reverseMessage: function () { this.message = this.message.split('').reverse().join('') } } })
  • 16. Getting started Two-way binding HTML <div id="app"> <p>{{ message }}</p> <input v-model="message"> </div> JS new Vue({ el: '#app', data: { message: 'Hello Vue.js!' } })
  • 17. Getting started Components allows us to build large-scale applications composed of small, Self-contained and often reusable components. A component is essentially a Vue instance with pre-defined options. Registering a component in Vue is straightforward: JS Vue.component('todo-item', { template: '<li>This is a todo</li>' }) Now you can compose it in another component’s template: HTML <ol> <todo-item></todo-item> </ol>
  • 18. Getting started But this would render the same text for every todo. We should be able to pass data from the parent scope into child components. Let’s modify the component definition to make it accept a prop: JS Vue.component('todo-item', { props: ['todo'], template: '<li>{{ todo.text }}</li>' })
  • 19. Getting started Now we can pass the todo into each repeated component using v-bind: HTML <div id="app"> <ol> <todo-item v-for="item in groceryList" v-bind:todo="item"></todo-item> </ol> </div> JS Vue.component('todo-item', { props: ['todo'], template: '<li>{{ todo.text }}</li>' }) new Vue({ el: '#app', data: { groceryList: [ { text: 'Vegetables' }, { text: 'Cheese' }, { text: 'Whatever else humans are supposed to eat' } ] } })
  • 20. Getting started TODO list example HTML <div id="todo"> <input type="text" placeholder="Add new task" @keyup.enter="addItem"/> <ul> <li v-for="item in items"> <span :class="{'done': item.done}">{{item.text}}</span> <button @click="toggleItem(item)">{{item.done ? 'Not done': 'Done'}}</button> <button @click="deleteItem(item)">Delete</button> </li> </ul> </div> JS new Vue ({ el: '#todo', data: { items: [] }, methods: { addItem (e) { this.items.push({ text: e.target.value, done: false }) e.target.value = '' }, toggleItem (item) { item.done = !item.done }, deleteItem (item) { this.items.splice(this.items.indexOf(item), 1) } } }) CSS .done { text-decoration: line-thorough; }
  • 21. Routing Single Page Application (SPA) 1. Entire app loaded on a single page 2. No page reload on UI navigation 3. Dynamically update UI with ajax-fetched data
  • 22. Dynamic page-level component // routes templates const NotFound = {template: '<p>404</p>'} const Home = {template: '<p>Home page</p>'} const About = {template: '<p>About page</p>'} // routes mapping let routes = { '/': Home, '/about': About } // vue instance new Vue({ el: '#app', data: { currentRoute: window.location.pathname }, computed: { ViewComponent () { return routes[this.currentRoute] || Notound } }, render (h) { return h(this.ViewComponent) } })
  • 23. Vue Router 1. Dynamic route matching (patterns) 2. HTML5 history API (states) 3. Lazy-loading (async components) 4. Nested routes 5. Navigation guards (authentication, preloading...)
  • 24. Vue CLI The simplest possible Vue setup in a single HTML file $ npm i -g vue-cli # Install vue-cli if you haven't already $ vue init simple # Create a new project based on this template $ cd simple # Navigate into your new project folder $ npm i -g live-server # Install live-server if you haven't already $ live-server # Run live-server and open it in your browser Current available templates include: webpack - A full-featured Webpack + vue-loader setup with hot reload, linting, testing & css extraction. webpack-simple - A simple Webpack + vue-loader setup for quick prototyping. browserify - A full-featured Browserify + vueify setup with hot-reload, linting & unit testing. browserify-simple - A simple Browserify + vueify setup for quick prototyping. simple - Vue setup in a single HTML file
  • 25. VUE CLI Vue router and preloading example $ npm i -g vue-cli $ vue init webpack-simple app $ cd app $ npm i $ npm run dev app /node_modules /src /assets Logo.png App.vue Main.js .babelrc index.html package.json README.md webpack.config.js
  • 26. Webpack simple $ npm i vue-router -S App.vue <template lang="pug"> #app //- caches the inactive component instances withouth destroying them keep-alive //- render current route template router-view </template> <script> export default { name: 'app' } </script>
  • 27. main.js import Vue from 'vue' import VueRouter from 'vue-router' import App from './App.vue' Vue.use(VueRouter) const Home = resolve => require(['./views/Home.vue'], resolve) const About = resolve => require(['./views/About.vue'], resolve) const NotFound = resolve => require(['./views/NotFound.vue'], resolve) const router = new VueRouter({ mode: 'history', routes: [ {path: '/', component: Home}, {path: '/about/:name?', component: About}, {path: '*', component: NotFound} ] }) const app = new Vue({ el: '#app', router, render: h => h(App) })
  • 28. Router mode ● Hash - uses the URL hash for routing (hashbang urls /#!/) ● History - uses HTML5 History API (semantic urls) ● Abstract - servre-side with Node.js (all javascript environments) Server config - nginx location / { try_files $uri $uri/ index.html }
  • 29. Lazy Loading Routes Async components to only load them when the route is visited: const Foo = resolve => require([‘./Foo.vue’], resolve) const Foo = () => System.import(‘./Foo.vue’) Built-in Component Caches inactive components withouth destroy them: <keep-alive></keep-alive> $ npm i vuex -S $ npm i vuex-router-sync@next -S
  • 30. store.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = { isPreloading: false } const mutations = { beginPreload (state) { state.isPreloading = true }, endPreload (state) { state.isPreloading = false } } const actions = { beginPreload: ({commit}) => commit('beginPreload'), endPreload: ({commit}) => commit('endPreload') } const getters = { isPreloading: state => state.isPreloading } export default new Vuex.Store({ state, getters, actions, mutations })
  • 31. preloader.vue <template lang="pug"> .preloader(:class="{'hidden': !this.$store.getters.isPreloading}") Loading... </template> <style scoped> .preloader { ... opacity: 1; visibility: visible; } .preloader.hidden { opacity: 0; visibility: hidden; } </style>
  • 32. App.vue <template lang="pug"> #app navigation preloader keep-alive router-view </template> <script> import Navigation from './partials/Nav.vue' import Preloader from './partials/Preloader.vue' export default { name: 'app', components: {Navigation, Preloader} } </script>
  • 33. main.js ... import store from './store' import {sync} from 'vuex-router-sync' const router = new VueRouter({ ... { path: '/about/:name?', component: About, meta: { preload: true } } ... }) router.beforeEach((to, from, next) => { if (to.matched.some(m => m.meta.preload)) { store.dispatch('beginPreload') next() } else { store.dispatch('endPreload') next() } }) sync(store, router) const app = new Vue({ el: '#app', router, store, render: h => h(App) })
  • 34. Navigation Guards Guard navigations either by redirecting it or canceling it: globally / per-route / in-component router.beforeEach((to, from, next) => {}) router.afterEach((to, from, next) => {}) ● to: Route : the target Route Object being navigated to. ● from: Route : the current route being navigated away from. ● next: Function : this function must be called to resolve the hook.
  • 35. Route Meta Fields Attach abstract information to each route: ● Authentication ● Preloading ● Authorized Referrer meta: { requiresAuth: true } router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAuth)) { // this route requires auth, check if logged in // if not, redirect to login page. if (!auth.loggedIn()) { next({ path: '/login', query: { redirect: to.fullPath } }) } else { next() } } else { next() // make sure to always call next() } })
  • 36. About.vue <template lang="pug"> div h1 About {{name}} </template> <script> export default { name: 'about', computed: { name () { return this.$route.params.name || 'anonymous' } }, activated () { setTimeout(() => { this.$nextTick(() => { this.$store.dispatch('endPreload') }) }, 3000) } } </script> Github: https://github.com/daliborgogic/vue-routing-preloading