
- VueJS - Home
- VueJS - Overview
- VueJS - Environment Setup
- VueJS - Introduction
- VueJS - Instances
- VueJS - Template
- VueJS - Components
- VueJS - Computed Properties
- VueJS - Watch Property
- VueJS - Binding
- VueJS - Events
- VueJS - Rendering
- VueJS - Transition & Animation
- VueJS - Directives
- VueJS - Routing
- VueJS - Mixins
- VueJS - Render Function
- VueJS - Reactive Interface
- VueJS - Examples
Vue.js Cheatsheet
In this cheat sheet, we will cover the essential features and concepts of Vue.js, including components, templates, directives, and reactivity. We will learn how to handle user interactions, manage state, and work with dynamic data. Whether building simple interfaces or complex single-page applications, this guide will provide quick references and practical snippets to help you work more efficiently with Vue.js.
Table of Contents
- Introduction
- Vue Basics
- Lifecycle Hooks
- Template Syntax
- Directives
- Reactivity
- Handling Events
- List Rendering
- Binding Data
- Parent-Child Communication
- Slots
- State Management
- Routing
- Dynamic Components
- Composition API
- Computed Properties
- Watchers
- Global Methods
- Testing
- Performance Optimization
Introduction to Vue.js
Vue.js is a progressive framework based on JavaScript that is mostly used for developing user interfaces. Developed by Evan You in 2014, Vue is reactive, lightweight, and especially concerned with the view layer and can be easily implemented with other libraries or projects. It is most suitable for SPAs and dynamic interfaces; the application where UX is immensely important.
Vue Basics
Data Binding
Data binding in Vue.js allows you to connect the data in your JavaScript code to the DOM, enabling dynamic updates when the data changes.
<script setup> import { ref } from 'vue' const message = ref('Hello, Vue!') const dynamicHtml = ref('<h2>This is dynamic HTML</h2>') </script> <template> <p>{{ message }}</p> <div v-html="dynamicHtml"></div> </template>
Attribute Binding
In Vue.js, attribute binding allows you to dynamically set attributes like src, href, and class using v-bind. This ensures that attributes are automatically updated when the bound data changes.
<script setup> import { ref } from 'vue' const dynamicId = ref('uniqueId') </script> <template> <!-- Passing `dynamicId` as an attribute --> <div v-bind:id="dynamicId"></div> <!-- `:id` is a shorthand of `v-bind:id` --> <div :id="dynamicId"></div> <!-- It can be passed directly without specifying a value, using the same name as the attribute --> <div v-bind:id></div> <!-- `:id` is a shorthand of `v-bind:id` --> <div :id></div> </template>
Event Bindings
Event bindings in Vue.js allow you to listen for and respond to DOM events such as clicks, input changes, or key presses using v-on. This helps trigger methods or actions when specific events occur.
<script setup> import { ref } from 'vue' const doThis = () => { console.log('Button clicked!') } </script> <template> <!-- Method handler --> <button v-on:click="doThis"></button> <!-- Shorthand --> <button @click="doThis"></button> </template>
Dynamic Binding
Dynamic binding in Vue.js enables you to bind data to various properties, including classes, styles, and content, allowing for responsive and real-time updates in your application.
<script setup> import { ref } from 'vue'; const text = ref('Vue') const count = 10 const isActive = false const suffix = 'element' </script> <template> <!-- JavaScript Expression inside mustache syntax --> {{ count * 2 }} {{ isActive ? 'Active' : 'Inactive' }} {{ text.value.toUpperCase() }} <div :class="`box-${suffix}`">Class Binding</div> </template>
Lifecycle Hooks
Lifecycle hooks in Vue.js are special methods that allow you to hook into different stages of a component's lifecycle. These hooks provide opportunities to run code during a component's creation, update, and destruction process.
Hook | Explanation |
---|---|
onBeforeMount | Before mounting to the DOM |
onMounted | After mounting to the DOM |
onBeforeUpdate | Before updating reactive data |
onUpdated | After updating the DOM |
onBeforeUnmount | Before unmounting |
onUnmounted | After unmounting |
Template Syntax
Text Interpolation
In Vue.js, text interpolation is used to insert dynamic data into the template of HTML. It is done using the {{ }} syntax, which automatically updates the displayed content whenever the bound data changes
<span>{{ msg }}</span> <span v-text="msg"></span> Setting Inner HTML:
Setting Inner HTML
To set raw HTML inside an element, you can use the v-html directive. This allows you to bind HTML content directly to an elements innerHTML, ensuring the content is rendered as HTML, not plain text.
<span v-html="rawHTML"></span>
Using JS Expressions
✅{{ msg.reverse() }}
❌ {{ let msg = 'hi' }}
Template Refs
Template refs in Vue.js allow you to reference DOM elements or child components directly within your template. You can access these references in your script using the ref function.
<script setup> import { ref, onMounted } from 'vue' // Declare a ref to hold the element reference const textInput = ref(null) onMounted(() => { textInput.value.select() }) </script> <template> <input ref="textInput" /> </template>
Directives
Directives in Vue.js are special tokens in the markup that bind DOM elements to Vues reactive data system. They are prefixed with v- and offer a declarative way to handle behavior in the template.
Directive | Explanation |
---|---|
v-if | Inserts/deletes element depending upon a specific condition |
v-else-if | Conditional continuation |
v-else | Fallback condition |
v-show | Shows or hides an element on a webpage when a button is clicked (CSS) |
v-text | Sets inner text |
v-html | Sets inner HTML |
v-for | Loops over arrays/objects |
v-on / @ | Listens for DOM events |
v-bind / : | Binds reactive attributes |
v-model | Two-way data binding |
v-once | Renders element only once |
Reactivity
Reactivity in Vue.js is a core feature that allows the framework to update the DOM when data changes automatically.
Feature | Syntax | Description |
---|---|---|
Reactive | const var = ref(value) | Creates reactive primitive values. |
Reactive Objects | const obj = reactive({ key: value }) | Makes entire objects reactive. |
Computed | const comp = computed(() => expression) | Creates a computed property. |
Watch | watch(var, callback) | Watches a variable for changes. |
Event Binding | @event="method" or v-on:event="method" | Binds event listeners to methods. |
Conditional Rendering | v-if="condition" / v-else-if="condition" / v-else | Conditionally renders elements. |
List Rendering | v-for="item in array" :key="item.id" | Renders a list of items from an array. |
Two-Way Binding | v-model="value" | Creates two-way binding for form elements. |
Destructuring Reactivity | const { prop } = reactiveObj | Destructuring reactive objects (use with caution). |
Handling Events
Events in Vue.js are handled by allowing you to respond to user interactions like clicks, key presses, and more. Vues event-handling system makes it easy to bind methods or actions to DOM events.
Event Listener
In Vue, you can bind an event listener to an element using the v-on directive.
<div v-on:click="handleClick"></div> <!-- Shorthand --> <div @click="handleClick"></div>
Event Modifiers
Event Modifiers in Vue.js enhance event handling by modifying event behavior, such as preventing default actions, stopping propagation, or limiting the listener to trigger once.
Modifier | Explanation |
---|---|
.stop | Stops event propagation |
.once | Event triggers only once |
.prevent | Prevents default browser behavior |
.self | Only triggers on current element |
List Rendering
List Rendering in Vue.js allows you to dynamically render lists of items from arrays or objects using the v-for directive. This helps create flexible and responsive templates that automatically update when the underlying data changes.
Loop over Array
In Vue.js, you can loop through an array and render each item by iterating over its elements.
<li v-for="item in items" :key="item.id">{{ item }}</li>
Loop with Index
When iterating over an array, you can also access the index of each item in the array.
<li v-for="(item, index) in items">{{ index }}: {{ item }}</li>
Loop Object Values
In addition to arrays, you can also loop through objects in Vue.js. This allows you to render both the keys and the values of an object.
<li v-for="(value, key) in object">{{ key }}: {{ value }}</li>
Rendering Example
<script setup> import { ref } from 'vue' // Sample data for list rendering const items = ref(['Item 1', 'Item 2', 'Item 3']) // Conditional rendering with a boolean flag const isLoggedIn = ref(false) // Data for scoped slot const user = ref({ name: 'John Doe', age: 30 }) </script> <template> <!-- Conditional rendering using v-if --> <p v-if="isLoggedIn">Welcome back, user!</p> <p v-else>Please log in to continue.</p> <!-- Rendering a list with v-for --> <ul> <li v-for="item in items" :key="item">{{ item }}</li> </ul> <!-- Using a scoped slot to customize content --> <UserProfile :user="user"> <template v-slot:default="{ user }"> <h3>User Info</h3> <p>Name: {{ user.name }}</p> <p>Age: {{ user.age }}</p> </template> </UserProfile> </template> <!-- Scoped Slot Component --> <template #UserProfile="{ user }"> <div> <slot :user="user"></slot> </div> </template>
Binding Data
Simple Binding
Binds data to an element's attribute or content, using the {{ }} syntax to insert dynamic data into the DOM.
<div v-bind:id="dynamicId"></div> <!-- Shorthand --> <div :id="dynamicId"></div>
Two-Way Binding
Enables bidirectional data flow between an input field and a component's data using v-model, automatically updating both the UI and the data.
<input v-model="text" />
Input Modifiers
Input Modifiers in Vue.js provide additional control over how to input data is handled during two-way binding.
Modifier | Explanation |
---|---|
.lazy | Updates on change event |
.trim | Trims whitespace in input |
Parent-Child Communication
Parent-child communication in Vue.js allows components to exchange data or trigger actions between each other.
Parent to Child
The parent component can pass data to the child component via props. For example, the parent passes a value to the child
app.get('/status', (req, res) => { res.status(200).json({ status: 'OK' }); });
Child to Parent
The child component can send data or events to the parent by emitting an event. The parent listens for this event and handles it accordingly.
this.$emit('eventName', payload);
Slots
Slots allow child components to inject dynamic content into a parent component.
Basic Slot
Slots provide a way to pass content from the parent to the child component. The content inside the <child> tag is passed into the childs slot.</child>
<!-- Child --> <slot></slot> <!-- Parent --> <child>Injected Content</child>
Named Slots
Named Slots allow you to define multiple slots in a child component, and the parent can specify content for each slot by name.
<!-- Child --> <slot name="header"></slot> <slot name="footer"></slot> <!-- Parent --> <child> <template v-slot:header>Header Content</template> <template v-slot:footer>Footer Content</template> </child> <!-- Child --> <slot v-bind:data="someData"></slot> <!-- Parent --> <child> <template v-slot:default="{ data }">{{ data }}</template> </child>
State Management
State Management in Vue.js allows you to manage and share state across components efficiently. Vuex is the official state management library for Vue.js, providing a centralized store for managing state and actions within your application.
Vuex
Vuex is a state management library that helps manage the state of an application in a centralized way. It enables components to access and modify the shared state without needing to pass props through many layers of components.
import { createStore } from 'vuex' const TodoListstore = createStore({ state() { return { todoListItems: [] } }, actions: { addNewList({ commit }, item) { { commit('createNewItem', item) } }, mutations: { createNewItem(state, item) { state.todoListItems.push(item) } } })
Pinia
Pinia is the modern state management library for Vue.js, designed to replace Vuex with a simpler API and better integration with Vue 3's Composition API.
import { defineStore } from 'pinia' Export const useListStore = defineStore('list', { state() => ({ return { todoListItems: [] } }), actions: { addNewList() { this.todoListItems.push(item) } }})
Routing
Routing in Vue.js is handled by the Vue Router library, which enables you to define and manage different views or pages in a single-page application (SPA).
VueRouter class and define your routes
The VueRouter class is used to create a router instance that manages navigation in a Vue.js application by mapping URL paths to components.
import Vue from 'vue' import Router from 'vue-router' import Home from './views/Home.vue' import About from './views/About.vue' Vue.use(Router) const router = new Router({ routes: [ { path: '/', name: 'home', component: Home }, { path: '/about', name: 'about', component: About } ] })
Navigating Between Routes
<template> <div> <h1>Home</h1> <router-link to="/about">Go to About</router-link> </div> </template>
Dynamic Components
Dynamic Components in Vue.js allow you to render different components dynamically based on certain conditions.
Render dynamic components
Render a component dynamically by binding the is attribute to a variable that holds the name of the component
<component :is="componentName" />
Cache dynamic components
<keep-alive> <component :is="componentName" /> </keep-alive>
Composition API
The Composition API in Vue.js is a set of API features that allows you to organize and reuse logic within components more effectively, especially in larger applications.
import { ref, reactive } from 'vue'; setup() { const message = ref('Hello Vue 3'); const state = reactive({ count: 0 }); const increment = () => state.count++; return { message, state, increment }; }
Computed Properties
Computed properties in Vue.js are values that are derived from other reactive properties. They are cached and only re-evaluated when their dependencies change.
Reactive value based on other properties
const double = computed(() => count.value *2);
Watchers
Watchers allow you to react to changes in reactive data. You can watch a specific reactive property or effect, and perform actions when it changes.
Watch a reactive dependency
watchEffect(() => { console.log(variable.value); });
Global Methods
Global methods are utility functions provided by Vue to assist in managing the lifecycle, reactivity, and rendering of components.
Method | Explanation |
---|---|
mount() | Mount the component to the DOM |
forceUpdate() | Force a re-render |
nextTick() | Runs function after DOM update |
Testing
Unit Test Example
Tests individual components or functions in isolation, focusing on specific features like rendering, logic, and user interactions.
import { shallowMount } from '@vue/test-utils'; import Foo from './Foo.vue'; // Factory function for test setup const factory = (values = {}) => { return shallowMount(Foo, { data() { return { ...values }; }, }); }; describe('Foo Unit Tests', () => { it('renders the welcome message', () => { const wrapper = factory(); expect(wrapper.find('.message').text()).toBe('Welcome to the Vue.js cookbook'); }); it('shows error for usernames less than 7 characters', () => { const wrapper = factory({ username: 'Vue' }); expect(wrapper.find('.error').exists()).toBe(true); }); it('shows error for whitespace-only usernames', () => { const wrapper = factory({ username: ' ' }); expect(wrapper.find('.error').exists()).toBe(true); }); it('hides error for usernames with 7+ characters', () => { const wrapper = factory({ username: 'Lachlan' }); expect(wrapper.find('.error').exists()).toBe(false); }); });
Integration Testing
Tests how multiple components and systems work together, ensuring data flows and interactions function correctly in a broader context.
import { mount } from '@vue/test-utils'; import Foo from './Foo.vue'; describe('Foo Integration Tests', () => { it('renders the initial state with error', () => { const wrapper = mount(Foo); // Check initial message expect(wrapper.find('.message').text()).toBe('Welcome to the Vue.js cookbook'); // Check for error expect(wrapper.find('.error').exists()).toBe(true); expect(wrapper.find('.error').text()).toBe('Please enter a username with at least seven letters.'); }); it('removes error when a valid username is entered', async () => { const wrapper = mount(Foo); // Simulate input change const input = wrapper.find('input'); await input.setValue('Lachlan'); // Error should not exist expect(wrapper.find('.error').exists()).toBe(false); }); it('shows error when whitespace-only username is entered', async () => { const wrapper = mount(Foo); // Simulate input change const input = wrapper.find('input'); await input.setValue(' '); // Error should exist expect(wrapper.find('.error').exists()).toBe(true); }); });
Performance Optimization
Lazy Loading Components
Lazy loading delays the loading of a component until it is required. This is typically used in routing to improve initial load times by splitting the application into smaller chunks.
const routes = [ { path: '/about', component: () => import('./components/About.vue'), // Lazy-loaded }, ];
Efficient Toggling with V-show
The v-show directive is used to toggle the visibility of an element by applying CSS display: none instead of adding or removing the element from the DOM.
<template> <div> <button @click="show = !show">Toggle</button> <div v-show="show">This is a toggled element</div> </div> </template> <script> import { ref } from 'vue'; export default { setup() { const show = ref(false); return { show }; }, }; </script>