SlideShare una empresa de Scribd logo
1 de 37
Descargar para leer sin conexión
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!

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Basics of Vue.js 2019
Basics of Vue.js 2019Basics of Vue.js 2019
Basics of Vue.js 2019
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
 
A la découverte de vue.js
A la découverte de vue.jsA la découverte de vue.js
A la découverte de vue.js
 
Vue, vue router, vuex
Vue, vue router, vuexVue, vue router, vuex
Vue, vue router, vuex
 
Vue.js for beginners
Vue.js for beginnersVue.js for beginners
Vue.js for beginners
 
Webpack slides
Webpack slidesWebpack slides
Webpack slides
 
Basics of VueJS
Basics of VueJSBasics of VueJS
Basics of VueJS
 
Nuxtjs cheat-sheet
Nuxtjs cheat-sheetNuxtjs cheat-sheet
Nuxtjs cheat-sheet
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
Deep dive into Vue.js
Deep dive into Vue.jsDeep dive into Vue.js
Deep dive into Vue.js
 
Vue Vuex 101
Vue Vuex 101Vue Vuex 101
Vue Vuex 101
 
Nuxt.JS Introdruction
Nuxt.JS IntrodructionNuxt.JS Introdruction
Nuxt.JS Introdruction
 
Spring Boot & Actuators
Spring Boot & ActuatorsSpring Boot & Actuators
Spring Boot & Actuators
 
An Overview on Nuxt.js
An Overview on Nuxt.jsAn Overview on Nuxt.js
An Overview on Nuxt.js
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Meetup angular http client
Meetup angular http clientMeetup angular http client
Meetup angular http client
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Life Cycle hooks in VueJs
Life Cycle hooks in VueJsLife Cycle hooks in VueJs
Life Cycle hooks in VueJs
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 

Similar a Love at first Vue

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
 

Similar a Love at first Vue (20)

Meet VueJs
Meet VueJsMeet VueJs
Meet VueJs
 
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
 
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
 
Vue js and Dyploma
Vue js and DyplomaVue js and Dyploma
Vue js and Dyploma
 
Building Progressive Web Apps for Windows devices
Building Progressive Web Apps for Windows devicesBuilding Progressive Web Apps for Windows devices
Building Progressive Web Apps for Windows devices
 

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

Último

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
Kayode Fayemi
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
raffaeleoman
 
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
Kayode Fayemi
 

Último (20)

Presentation on Engagement in Book Clubs
Presentation on Engagement in Book ClubsPresentation on Engagement in Book Clubs
Presentation on Engagement in Book Clubs
 
Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510
 
Report Writing Webinar Training
Report Writing Webinar TrainingReport Writing Webinar Training
Report Writing Webinar Training
 
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
 
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
 
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
 
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
 
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
 
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
 
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptx
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptxMohammad_Alnahdi_Oral_Presentation_Assignment.pptx
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptx
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
 
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
 
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
 
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-...
 
BDSM⚡Call Girls in Sector 97 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 97 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 97 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 97 Noida Escorts >༒8448380779 Escort Service
 
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night EnjoyCall Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
 
Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)
 
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
 
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
 
SaaStr Workshop Wednesday w/ Lucas Price, Yardstick
SaaStr Workshop Wednesday w/ Lucas Price, YardstickSaaStr Workshop Wednesday w/ Lucas Price, Yardstick
SaaStr Workshop Wednesday w/ Lucas Price, Yardstick
 

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