Vuejs Essentials
Vuejs Essentials
Vuejs Essentials
Vue.js essentials
Paul Nta
1 . 1
📝 Plan 1. Vue minimal setup
2. List rendering
3. Conditional rendering
4. Events
5. Computed properties
6. Classes & Styles binding
7. Components
8. Single file components
9. Routing
10. State managment
1 . 2
🎯 Goals
A quick tour of the most
important Vue.js features
2 . 1
Why
Choosing
Vue.js?
Declarative rendering
Components
State management
Client side routing
2 . 2
1. Vue minimal
setup
3 . 1
Minimal setup
or
3 . 2
Minimal setup
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>Music app</title>
7 </head>
8 <body>
9 <div id="app">
10 <h1>{{ title }}</h1>
11 </div>
12 <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
13 <script>
14 const app = new Vue({
15 el: "#app",
16 data: {
17 title: "Hello world"
18 }
19 });
20 </script>
21 </body>
22 </html>
3 . 3
The Vue instance
3 . 4
Subtitle
<div id="app">
<!-- This part of the DOM is now controlled by Vue -->
</div>
<script>
var vm = new Vue({
el: '#app'
})
</script>
3 . 5
Data binding
<div id="app">
<h1>{{ message }}</h1>
</div>
<script>
const vm = new Vue({
el: '#app',
data: {
message: 'Hello world',
}
})
</script>
<div id="app">
<h1>{{ message }}</h1> All the properties found in
</div>
the data object are reactive
<script>
const vm = new Vue({
When the values of those
el: '#app', properties change, the view
data: {
message: 'Hello world',
will “react”, updating to
} match the new values.
})
3 . 7
Data binding
3 . 8
Attribute binding
<h1 v-bind:id="titleId"></h1>
Shortand
<h1 :id="`title-${count}`"></h1>
<button :disabled="isButtonDisabled"></button>
<h1 :id="`title-${count}`"></h1>
3 . 9
Vue.js essentials
2. List
rendering
tracks
4 . 1
List rendering
1 <div
2 v-for="track in tracks"
3 v-bind:key="track.id"
4 />
5 {{ track.title }}
6 </div>
7
4 . 2
List rendering
3. Conditional
rendering
5 . 1
Lifecycle hooks
<div v-if="error">
Sorry it's broken
</div>
<div v-else-if="loading">
Wait....
</div>
<template v-else>
<div>{{ playlist.title }}</div>
<div v-for="track in tracks" v-bind:key="track.id">
{{ track.title }}
</div>
</div>
An element with v-show will always be rendered and remain in the DOM
5 . 4
Vue.js essentials
4. Events
select track
6 . 1
Events
1 <div
2 v-for="track in tracks"
3 v-bind:key="track.id"
4 />
5 <button v-on:click="selectTrack(track)">
6 Play
7 </button>
8 <span>{{ track.title }}</span>
9 </div>
new Vue({
el: '#app',
data: {
tracks: [/*...*/],
currentTrack: null
},
methods: {
selectTrack(track) {
this.currentTrack = track;
}
}
});
6 . 2
Events
Use v-on directive to listen to DOM events and run some JavaScript
when they’re triggered
6 . 3
Events modifiers
use enter event key modifier to only listen to a ENTER key press
<input v-on:keyup.enter="submit">
6 . 4
Form Input Bindings
It's common to implement two-way data bindings on form elements
such as input. The idea is to treat Vue instance data as the single source
of truth
1 <div id="app">
2 <input
3 type="text"
4 v-bind:value="searchText"
5 v-on:input="searchText = $event.target.value"
6 >
7 </div>
<script>
new Vue({
el: '#app',
data: {
searchText: ''
}
})
</script>
6 . 5
Form Input Bindings
You can use the v-model directive to create two-way data bindings on
form input, textarea, and select elements
<div id="app">
<input
type="text"
v-model="searchText"
>
</div>
This is essentially syntax sugar for updating data on user input events.
Under the hood, v-model implements v-bind:value and v-on:input
6 . 6
Vue.js essentials
5. Computed
properties
total duration
7 . 1
Methods
// ...
methods: {
getDuration() {
return this.tracks.reduce((acc, track) => acc + track.duration, 0)
}
}
7 . 2
Computed properties
//...
computed: {
duration() {
return this.tracks.reduce((acc, track) => acc + track.duration, 0)
}
}
7 . 3
Vue.js essentials
6. Classes
& Styles
binding
playing
track
8 . 1
Classes & styles binding
<div
v-for="track in tracks"
:key="track.id"
:class="{ isPlaying: track === currentTrack }"
/>
<button @click="currentTrack = track">Play</button>
...
</div>
Vue provides special enhancements when v-bind is used with class and
style attributes
In addition to strings, the expressions can also evaluate to objects or
arrays
8 . 2
Classes & styles binding
8 . 3
Vue.js essentials
7. Components
<track-item>
9 . 1
Components
Vue.component("track-item", {
props: ["title"],
template: '<div>{{ title }}</div>'
});
9 . 2
Components
Vue.component("track-item", {
props: ["title"],
template: '<div>{{ title }}</div>'
});
<track-item title="Despacito"></track-item>
<track-item title="Gangnam Style"></track-item>
9 . 3
Components
Vue.component("track-item", {
props: ["title"],
render(createElement) {
return createElement('div', this.title)
}
});
Under the hood, Vue compiles template strings into render functions.
In some rare case you may need to directly write render functions to
unlock the full power of Javascript.
Generally, it's better to use templates because they are easier to read
and much more concise
9 . 4
Components
Let's make our component a bit smarter
9 . 5
Components
You can render components multiple times with the v-for directive
and listen to custom events
<div id="#app">
⚠ DOM templates have the
<track-item
following restrictions:
v-for="track in tracks"
:key="track.id" Component names should be
:id="track.id" kebab-case
:title="track.title"
:is-playing="isPlaying(track)" Attributes should be kebab-
@play="selectTrack(track)" case
></track-item>
</div> Self closing elements are not
allowed
9 . 6
Component anatomy
Vue.component("my-component", {
props: {
title: String,
info: Object,
email: {
type: String,
required: true,
default: 'none',
validator() {
/* return true if value is valid */
}
},
},
data() { /* must be a function */ }
created() {},
mounted() {},
methods: {},
computed: {},
watch: {},
template: `<div>....</div>`
});
9 . 7
Vue.js essentials
8. Single file
components
10 . 1
Single file components
So far we looked at the minimal setup for a Vue app. This can work well
for simple projects, where Vue is only used to enhance certain views.
10 . 2
Single file
component
(SFC)
Syntax syntax highlighting
JS Modules
10 . 3
Setup a Vue project
10 . 4
Setup a Vue project
Initialize a project
10 . 6
Local component registration
Importing a component from a single-file component. This is called local
component registration
<template>
<TrackItem id="1" title="Despacito" isPlaying />
</template>
<script>
import TrackItem from "@/components/TrackItem.vue";
export default {
components: { TrackItem },
};
</script>
10 . 7
Vue.js essentials
9. Routing
/ /playlist/:id
11 . 1
Single page applications (SPA)
11 . 2
Install Vue router
Vue router is an official plugin for Vue Router that helps link between
the browser's URL/History and Vue's components allowing for certain
paths to render whatever view is associated with it.
// main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
11 . 3
Configure Vue router
new Vue({
router,
el: '#app',
render: h => h(App)
})
11 . 4
Vue Router
App.vue can use <router-view /> to let Vue route render the correct component
based on the current URL
<template>
<div>
<!-- common header for all routes -->
<router-view />
<!-- common footer for all routes -->
</div>
</template>
// Playlist.vue
// path: /playlist/:id
export default {
created() {
const id = this.$route.params.id
}
}
11 . 5
Navigation
In the past, the only way to change the URL was to change the window.location
which always reloaded the page
window.location = '/playlist/12345';
Except, if all you changed was the hash (such as when you clicking on <a
href="#target">link</a>. This trick has been used in the past to allow client-side
routing.
Now, browsers implemented the HTML5 History API giving developers the ability
to modify a website URL without reloading the page
11 . 6
Navigation
Using <a href=""> will cause the page to reload
<template>
<a href="/playlist/12345">Link</a>
</template>
Instead, you can use the <router-link> global component to use the HTML5 History
API
<template>
<router-link to="/playlist/12345">Link</router-link>
</template>
11 . 7
Vue.js essentials
10. State
management currentTrack?
<Queue />
<Playlist />
currentTrack?
<Player />
currentTrack?
12 . 1
Component structure
12 . 2
Component structure
12 . 3
External store
Having an external store is more flexible
Components can
submit actions to
mutate the store
12 . 4
Vuex
Vuex is a state management pattern + library for
Vue.js applications
12 . 5
One-way data flow
12 . 6
Vuex
Installation
Vue.use(Vuex)
12 . 7
Vuex
Create store
12 . 8
Vuex
Create store
1 const store = new Vuex.Store({
2 state: {
3 currentTrack: null,
4 },
5 mutations: {
6 setCurrentTrack(state, track) {
7 state.currentTrack = track
8 }
9 },
10 actions: {
11 playTrack({ commit }, track) {
12 commit('setCurrentTrack', track)
13 }
14 }
15 });
16
17 new Vue({
18 el: '#app',
19 store: store,
20 //...
21 })
12 . 9
Vuex
<button @click="$store.actions.playTrack(track)">...
12 . 10
Questions ❓❔
13