This course was created by Maximilian Schwarzmüller
Vue.js is an awesome JavaScript Framework for building Frontend Applications! VueJS mixes the Best of Angular + React!
- Build amazing Vue.js Applications - all the Way from Small and Simple Ones up to Large Enterprise-level Ones
- Understand the Theory behind Vue.js and use it in Real Projects
- Leverage Vue.js in both Multi- and Single-Page-Applications (MPAs and SPAs)
- Learn the latest version of Vue (Vue 3), including the brand-new Composition API
- Vue.createApp() → Global
- Has an object to configure Vue:
- data → It is a function, everything returned by the data function can be used in the HTML controlled by Vue. Vue takes all the data in this object and merges it into a global instance Vue object, to access this global instance we need to use the keyword
this
. - methods → Allow you to define functions, it takes an object that holds as many functions as you may need.
- data → It is a function, everything returned by the data function can be used in the HTML controlled by Vue. Vue takes all the data in this object and merges it into a global instance Vue object, to access this global instance we need to use the keyword
const app = Vue.createApp({
data() {
return {
courseGoalsA: 'Finish the course and learn Vue!',
courseGoalsB: 'Master Vue and build amazing apps!',
vueLink: 'http://www.vuejs.org/',
};
},
methods: {
outputGoal() {
const randomNumber = Math.random();
return randomNumber < 0.5 ? this.courseGoalsA : this.courseGoalsB;
},
},
});
- We control all child elements of the HTML element mounted by Vue.
app.mount('#element-id');
A two-way binding (listening and writing through value attribute), makes Vue manage the property. A shortcut for a v-bind:value
and v-on:input
.
Add an event listener: <button v-on:click="addGoal">Add Goal</button>
This directive has a shorter version: @click
Loop thought the content of an array, creating an element for each one.
<ul>
<li v-for="goal in goals">{{ goal }}</li>
</ul>
Set a value to an attribute: <input type="text" v-bind:value="myName" />
This directive has a shorter version: :value
Insert HTML content, but has security issues:
<p v-html="myName"></p>
<script>
[...]
myName: "<h2>Diego Florença</h2>",
[...]
</script>
Any dynamic data binding, like interpolations, should only be evaluated once.
Modify a default event behaviour.
.prevent → Prevent a form submission
<form v-on:submit.prevent="submitForm">
.stop → Stop the event from happening, in this example without the .stop
modifier will be impossible to type in the input
without triggering the removeGoal
function.
<ul>
<li v-for="(goal, index) in goals" @click="removeGoal(index)">
{{ goal }}
<input type="text" @click.stop>
</li>
</ul>
- To insert text content on the page we use the interpolation method by adding
{{ variable/expression }}
- The interpolation only allows us to use simple JavaScript expressions or pure text, and always between HTML tags.
<section id="assignment">
<h2>{{ myName }}</h2>
<p>{{ myAge }}</p>
<p>Favorite Number: {{ Math.random() }}</p>
</section>
We can call a function using v-bind
or v-html
but these methods are not the best way for outputting some dynamically calculated values.
We can also call a function like this: {{ functionX() }}
, but this way Vue will automatically rerun this function on every change because it doesn`t know what this function does.
Use with event binding OR data binding.
const app = Vue.createApp({
data() {
return {
counter: 0,
name: '',
};
},
methods: {
setName(event, lastName) {
this.name = event.target.value + ' ' + lastName;
},
add(num) {
this.counter = this.counter + num;
},
reduce(num) {
this.counter = this.counter - num;
},
},
});
Data binding {{ }}
methods are executed for every “re-render” cycle of the component. Use for events or data that really needs to be re-evaluated all the time.
Used only with data binding, not with events. They are essentially like methods but Vue is aware of their dependencies and only re-execute them if one of the dependencies changed. Use for data that depends on other data.
const app = Vue.createApp({
data() {
return {
...
};
},
computed: {
fullname() {
console.log('Running again...');
if (this.name === '') return '';
return this.name + ' ' + 'Florença';
},
},
methods: {
...
},
});
Used as a data property not like a function: <p>Your Name: {{ fullname }}</p>
.
From the performance perspective using computed properties is better than methods for outputting values in most cases but events cannot be bound to computed properties.
Not used directly in template. A function that executes some logic when a bound property changes. Ideal to change a data property when something happens. Use for any non-data update you want to make.
const app = Vue.createApp({
data() {
return {
counter: 0,
name: '',
fullname: '',
};
},
watch: {
counter(value) {
if (value > 50) {
this.counter = 0;
}
},
},
});
Allows you to run any code in reaction to some changed data. Could be used with HTTP requests or timers.
Vue supports a dynamic class :class
that can be applied when a data property is true.
<section id="styling">
<div class="demo" :class="{active: boxASelected}" @click="boxSelected('A')"></div>
<div class="demo" :class="{active: boxBSelected}" @click="boxSelected('B')"></div>
<div class="demo" :class="{active: boxCSelected}" @click="boxSelected('C')"></div>
</section>
data() {
return {
boxASelected: false,
...
};
},
methods: {
boxSelected(box) {
if (box === 'A') {
this.boxASelected = !this.boxASelected;
} ...
}
},
},
A better approach for complexes use cases could be to use computed properties to keep the logic separated from the HTML.
<section id="styling">
<div class="demo" :class="boxAClasses" @click="boxSelected('A')"></div>
<div class="demo" :class="boxBClasses" @click="boxSelected('B')"></div>
<div class="demo" :class="boxCClasses" @click="boxSelected('C')"></div>
</section>
computed: {
boxAClasses() {
return { active: this.boxASelected };
}, ...
},
It`s also possible to use an array as classes, this could allow more dynamic changes in styling.
Add a condition to render the element the expression must return true
or false
.
<p v-if='goals.length === 0'>No goals have been added yet - please start adding some!</p>
They must be used on the element that is directly after the element with v-if
on it.
<p v-if="goals.length === 0">...</p>
<ul v-else>
<li>Goal</li>
</ul>
The elements impacted by the v-if
directive are removed from the DOM
.
The v-show
directive works similarly to v-if
but it doesnt remove the element, it just change the display style to none:
display: none`.
<p v-show='goals.length === 0'>...</p>
Normally used on elements that changes visibility a lot.
Like a normal for
in JavaScript, we can use for to loop through an array of content or an object.
<ul v-else>
<li v-for='goal in goals'>{{ goal }}</li>
</ul>
It`s possible to get the index of the item in the array.
<li v-for='(goal, index) in goals'>
{{ goal }} - {{ index }}
</li>
To remove an item from an array we can create a method that uses splice
and pass the index of the item through a property of the function.
<li v-for="(goal, index) in goals" @click="removeGoal(index)">{{ goal }}</li>
methods: {
removeGoal(idx) {
this.goals.splice(idx, 1);
},
When using v-for
it`s important to keep track of the elements because of the way Vue works internally, without this specific attribute Vue will not know which element is which and this could create unexpected behaviour.
<li v-for="(goal, index) in goals" :key="goal">{{ goal }}</li>
This key must be unique, the index of the array will not be a good idea because it changes every time we remove an item from the array, the index is not attached to the data. In this example, the goal is a better option.
Another way to bind properties to the HTML
elements.
<input type="text" ref="userText" />
this.userInput = this.ref.userText.value;
JavaScript is not reactive, Vue use Proxies from JavaScript to keep track of changes.
Vue keeps track of all your data properties and whenever such a property changes, it updates the part of your app where that property was used.
You can have more than one app but they will not communicate between themselves.
Components are reusable pieces of HTML
with connected data and logic like an app inside an app, components are render elements directly from Vue. The v-for
directive is used to output simple data not complex HTML
elements with particular features.
- Vue uses a declarative approach instead of regular JavaScript which normally uses an imperative approach (step-by-step). We decide the end results, not how to get them.
- It is a good practice not to put too much logic on your HTML code, the HTML code should be about outputting stuff.
- We can use separate normal JavaScript
funcitons
when dealing with variable that are not related to theVue
like auxiliar functions to obtain a random number.function getRandomValue(min, max) { return Math.floor(Math.random() * (max - min)) + min; }