Vue.js Cheat Sheet Basics
I love Vue.js and enjoy using it for all my current projects. And I'll give you an overview of almost all basic Vue.js concepts. All this information is based on the official documentation, and I extend it with some more detailed knowledge.
Furthermore, I update this article in the future if new things come out or change. So it's worth to check this article from time to time.
Table of Content
Interpolations
Vue.js is a system that enables us to render data to the DOM using straightforward template syntax declaratively, which is possible by using Vue's double-mustache syntax.
Basic Interpolation
The data and the DOM are linked, and everything is reactive. Open your browser’s JavaScript console and set app.name
to a different value. You should see the rendered example update immediately.
<div id="app">
My name is: {{ name }}
</div>
var app = new Vue({
el: '#app',
data: {
name: 'Mario'
}
})
Note that you no longer have to interact with the HTML directly. A Vue app attaches itself to a single DOM element, #app
in this case, then fully controls it. The HTML is the entry point, but everything else happens within the created Vue instance.
Interpolation with Expression
Interpolations can contain simple expressions in Vue, like this:
<div>{{ bugs + 99 }} little bugs in the code</div>
Manipulate your local data with methods, where you can change an array to a comma-separated string for example.
<div>On my shopping list is: {{ list.join(", ") }}</div>
You can also use a ternary operator to have a conditional rendering.
<div>You {{ score > 50 ? 'passed' : 'failed' }} the test</div>
Important to know:
- You can only use one expression inside an interpolation
- I highly recommend to use for advanced string manipulation computed properties
- Statements doesn't work
<!-- THIS IS WRONG -->
{{ let message = 'Hello World!'; }}
- Regular conditions doesn't work
<!-- THIS IS WRONG -->
{{ if(status) { return message } }}
Directives
Directives are unique attributes with the v- prefix. The job is to reactively apply side effects to the DOM when the value of its expression changes.
Regular Attribute Binding
You can manipulate every HTML attribute by using the v-bind
directive. Binding means that you use your data inside a tag's attribute. One example is setting the href attribute of an anchor tag.
<a v-bind:href="url"></a>
If you want to combine a string with you local data, then put your string inside of single quotes and concat it.
<a v-bind:href="baseUrl + '/article/' + id"></a>
A common need is also conditional binding. For the attributes which don't have a value like disabled from a button.
<!-- With local data which return a boolean -->
<button v-bind:disabled="isDisabled"></button>
<!-- With expression which return a boolean -->
<button v-bind:disabled="password.length < 8"></button>
Important to know:
For frequently used directives like v-bind
you can use a nice shorthand by simply using a colon
<!-- full syntax -->
<a v-bind:href="url"></a>
<!-- shorthand -->
<a :href="url"></a>
Something wrong that new Vue developers try to do is putting data into a attribute like this:
<!-- THIS IS WRONG -->
<a href="baseUrl + '/article/' + id"></a>
Don't forget the colon or v-bind directive.
Class Bindings
A common need is manipulating an element's class list.
Object Syntax
You can pass an object to v-bind:class
to dynamically toggle a CSS class:
<div v-bind:class="{ active: isActive }"></div>
You can have multiple classes toggled by having more fields in the object.
<div v-bind:class="{ active: isActive, 'dark-theme': isDark }"></div>
The above syntax means the presence of the active and 'dark-theme' classes will be determined by the truthiness of the data property isActive and isDark.
The v-bind:class
directive can also co-exist with the plain class attribute.
<div class="main" v-bind:class="{ active: isActive, 'dark-theme': isDark }"></div>
With the following local data
data: () => {
return {
isActive: true,
isDark: false
}
}
It will render this, in the end:
<div class="main active"></div>
Array Syntax
Another syntax you can use for class bindings is passing an array to v-bind:class
.
<div v-bind:class="[activeClass, darkClass]"></div>
data: () => {
return {
activeClass: 'active',
darkClass: 'dark-theme'
}
}
It’s also possible to mix them up and use the object syntax inside array syntax:
<div v-bind:class="[{ active: isActive }, darkClass]"></div>
Inline Style Bindings
The object syntax for v-bind:style
is pretty straightforward - it looks almost like CSS, except it's a JavaScript object. You can use either camelCase or kebab-case (use quotes with kebab-case) for the CSS properties.
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
data: () => {
return {
activeColor: '#00ff00',
fontSize: 16
}
}
Two-Way Data Binding
By using the v-model
directive, you can create a two-way data binding. This means the user can change the data using an input field and see the result simultaneously. The directive can work on almost every input type.
<input v-model="someValue" name="someName" />
<div>The value is: {{ someValue }}</div>
data: () => {
return {
someValue: ''
}
}
Rendering HTML
If you don't want to escape your data and render it as plain HTML use the v-html
directive:
<div v-html="someHtml"></div>
Important to know:
Dynamically rendering HTML on your website can be very dangerous because it can easily lead to XSS attacks. Only use v-html
on trusted content and never on user-provided content.
Conditional Rendering
The directive v-if
is used to conditionally render an element and will only be rendered if the directive’s expression returns a truthy value.
<h1 v-if="awesome">Vue is awesome!</h1>
It is also possible to add with v-else
an "else block". It must immediately follow a v-if
element. Otherwise it will not be recognized.
<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no 😢</h1>
The v-else-if
serves as an "else if block" for v-if
. It can also be chained multiple times. Similar to v-else
, a v-else-if
element must immediately follow a v-if
or a v-else-if
element.
<button v-if="type === 'button'"></button>
<div v-else-if="type === 'div'"></div>
<a v-else-if="type === 'url'"></a>
<span v-else></span>
Conditional Display
Another option for conditionally displaying an element is the v-show
directive. The usage is largely the same:
<h1 v-show="true">Hello World!</h1>
The difference is that an element with v-show
will always be rendered and remain in the DOM and only toggles the display CSS property of the element.
Important to know:
v-show
doesn't work with v-elsev-show
actually renders but hides the element.v-if
is lazy which means the element with false condition at the beginning won't be rendered
In general, v-if
has higher toggle costs while v-show
has higher initial render costs. So prefer v-show
if you need to toggle something very often, and prefer v-if
if the condition is unlikely to change at runtime.
List Rendering
You can use the v-for
directive to render a list of items based on an array. The v-for directive requires a special syntax in the form of "item in items", where "items" is the source data array and "item" is an alias for the array element being iterated on.
<ul>
<li v-for="item in items" :key="item.message">
{{ item.message }}
</li>
</ul>
data: () => {
return {
items: [
{ message: 'Foo' },
{ message: 'Bar' }
]
}
}
You can also use v-for
to iterate through the properties of an object.
<ul>
<li v-for="value in object" :key="value">
{{ value }}
</li>
</ul>
data: () => {
return {
object: {
title: 'How to loop in Vue',
author: 'Mario Laurich',
publishedAt: '2020-07-31'
}
}
}
You can also provide a second argument for the property’s name.
<div v-for="(value, name) in object" :key="value.name">
{{ name }}: {{ value }}
</div>
And another for the index.
<div v-for="(value, name, index) in object" :key="value.name">
{{ index }}: {{ name }} - {{ value }}
</div>
Important to know:
- It is necessary to provide a key attribute
- Duplicate keys will cause render errors
Iterating in a range of numbers is also pretty easy
<div>
<span v-for="n in 10">{{ n }}</span>
</div>
Events
You can use the v-on
directive to listen to DOM events and run some JavaScript or methods when they’re triggered.
<button v-on:click="counter += 1">Add 1</button>
<p>The button above has been clicked {{ counter }} times.</p>
data: () => {
return {
counter: 0
}
}
Important to know:
For frequently used events like v-on
you can use a nice shorthand by simply using @
<!-- full syntax -->
<button v-on:click="counter += 1">Add 1</button>
<!-- shorthand -->
<button @click="counter += 1">Add 1</button>
Conclusion
That was the first part of almost all the basic concepts of Vue.js. I wanted to create a summary for myself, and I hope that it will also help you.
You miss something? I'll add watchers, computed properties and other basic stuff soon. 🙂
Let's connect
Follow me on YouTube and Twitter. That's where I usually hang out. The other platforms is a nice to have if you are a real webnoob fan ;)