The Vue.js Cheat Sheet
By Flavio Copes
A Vue.js 3 cheat sheet covering directives, form bindings, event modifiers, lifecycle hooks, createApp, and the options you use day to day.
- Directives
- Working with form elements
- Modifying events
- Mouse event modifiers
- Submit an event only if a particular key is pressed
- Keyboard event modifiers
- Lifecycle Hooks
- Built-in components
- Creating an app
- Global APIs
- App config
- Component options
- Instance properties
Cheat sheet for Vue 3. Vue 2 reached end of life in December 2023, so use Vue 3 for new work.
Directives
Directives are attributes identified by the v- prefix.
| Directive | Description |
|---|---|
v-text | uses the property as the text value of the element |
v-html | uses the property as the text value of the element, interpreting HTML |
v-if | show an element only if the conditional is true |
v-else | shows an alternative element if the preceding v-if is false |
v-else-if | adds an else if block for a v-if construct |
v-show | similar to v-if, but adds the element to the DOM even if falsy. Just sets it to display: none. |
v-for | iterates over an array or iterable object |
v-on | listen to DOM events |
v-bind | reactively update an HTML attribute |
v-model | sets up a two-way binding for form inputs (and components via modelValue) |
v-slot | declare a named or scoped slot (# shorthand) |
v-pre | skip compilation for this element and its children |
v-once | applies the property just once, and never refreshes it even if the data passed changes |
v-memo | memoize a subtree; only re-render when a dependency in the array changes |
v-cloak | hidden until the component is compiled (pair with [v-cloak] { display: none }) |
v-bind and v-on have a shorthand format:
<a v-bind:href="url">...</a>
<a :href="url">...</a>
<a v-on:click="doSomething">...</a>
<a @click="doSomething">...</a>
Example of v-if / v-else / v-else-if:
<div v-if="type === 'A'">
it's A
</div>
<div v-else-if="type === 'B'">
it's B
</div>
<div v-else-if="type === 'C'">
it's C
</div>
<div v-else>
it's neither one
</div>
Conditionals
You can embed a conditional in an expression using the ternary operator:
{{ isTrue ? 'yes' : 'no' }}
Working with form elements
To make the model update when the change event occurs, and not any time the user presses a key, you can use v-model.lazy instead of just v-model.
Working with input fields, v-model.trim is useful because it automatically removes whitespace.
And if you accept a number instead than a string, make sure you use v-model.number.
On a custom component, v-model maps to the modelValue prop and the update:modelValue event. See how to use v-model.
Modifying events
I use click as an example, but applies to all possible events
v-on:click.stopstop the click event propagationv-on:click.passivemakes use of the passive option of addEventListenerv-on:click.captureuse event capturing instead of event bubblingv-on:click.selfmake sure the click event was not bubbled from a child event, but directly happened on that elementv-on:click.oncethe event will only be triggered exactly oncev-on:submit.prevent: callevent.preventDefault()on the triggered submit event, used to avoid a form submit to reload the page
.native is gone in Vue 3. Listen for native events on a component with a plain @click (or declare emits so Vue knows which listeners are component events).
For more on propagation, bubbling/capturing see my JavaScript events guide.
Mouse event modifiers
v-on:click.lefttriggers only on left mouse button clickv-on:click.righttriggers only on right mouse button clickv-on:click.middletriggers only on middle mouse button click
Submit an event only if a particular key is pressed
v-on:keyup.enterv-on:keyup.tabv-on:keyup.deletev-on:keyup.escv-on:keyup.upv-on:keyup.downv-on:keyup.leftv-on:keyup.right
Keyboard event modifiers
Only trigger the event if a particular keyboard key is also pressed:
.ctrl.alt.shift.meta(cmd on Mac, windows key on Win)
v-bind
v-bind.propbind a DOM property instead of an attributev-bind.cameluse camelCase for the attribute namev-bind.attralways bind as an attribute
.sync is gone in Vue 3. Use v-model:propName instead (expands to a prop plus update:propName).
Lifecycle Hooks
Options API names (Composition API equivalents in parentheses):
beforeCreate/created: setup runs before these; prefersetup()/<script setup>for init workbeforeMount(onBeforeMount) called before the app is mounted on the DOMmounted(onMounted) called after the app is mounted on the DOMbeforeUpdate(onBeforeUpdate) called before a reactive update is applied to the DOMupdated(onUpdated) called after a reactive update is applied to the DOMbeforeUnmount(onBeforeUnmount) called before the app is unmounted (wasbeforeDestroyin Vue 2)unmounted(onUnmounted) called after the app is unmounted (wasdestroyedin Vue 2)activated(onActivated) called when a kept-alive component is activateddeactivated(onDeactivated) called when a kept-alive component is deactivatederrorCaptured(onErrorCaptured) called when an error from a descendant is capturedrenderTracked/renderTriggered(onRenderTracked/onRenderTriggered): debug hooks for reactive dependency tracking, development mode only
Built-in components and special elements
Vue provides these built-in components and special template elements (<component> and <slot> are special elements, not components):
<component><transition><transition-group><keep-alive><slot><Teleport><Suspense>
Creating an app
Vue 3 apps start with createApp, not new Vue:
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
With inline options:
import { createApp } from 'vue'
createApp({
data() {
return {
message: 'Hello'
}
},
methods: {
reverseMessageAsMethod() {
return this.message.split('').reverse().join('')
}
},
computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
}
}
}).mount('#example')
Global APIs
These are imported from vue (or used on the app instance). Vue 2 globals like Vue.filter and Vue.set are gone: filters were removed, and Proxy-based reactivity makes Vue.set unnecessary.
| API | Description |
|---|---|
createApp | create an application instance |
nextTick | defer the callback until after the next DOM update cycle |
defineComponent | type helper for component options |
defineAsyncComponent | lazy-load a component |
h | create a VNode (hyperscript) |
ref / reactive / computed / watch / watchEffect | Composition API reactivity |
provide / inject | dependency injection |
onMounted and other on* helpers | Composition API lifecycle |
App instance methods:
| Method | Description |
|---|---|
app.component | register or retrieve a global component |
app.directive | register or retrieve a global directive |
app.use | install a plugin |
app.mixin | apply a global mixin (use sparingly) |
app.provide | provide a value to all descendants |
app.mount | mount the app on a DOM element |
app.unmount | unmount the app |
app.config | app-level configuration object |
App config
app.config has these properties:
| Property | Description |
|---|---|
errorHandler | set an error handler function. Useful to hook Sentry and other similar services |
warnHandler | set a warning handler function, similar to errorHandler, but for warnings |
globalProperties | add properties available on every component instance (this.foo in Options API) |
optionMergeStrategies | custom merge strategies for options |
performance | if true, traces component performance in Browser DevTools |
compilerOptions | runtime compiler options (whitespace, isCustomElement, comments, delimiters) |
isCustomElement | (via compilerOptions) let Vue ignore custom elements like Web Components |
Vue 2’s Vue.config.silent, keyCodes, and productionTip are gone or no longer needed.
Component options
When defining a component (or the root passed to createApp), you pass an options object.
| Property | Description |
|---|---|
data | a function that returns reactive state. Must be a function so each instance gets its own object |
props | attributes exposed to parent components as input data |
emits | declare events the component can emit |
methods | methods defined on the instance |
computed | like methods, but cached internally |
watch | watch properties, and call a function when they change |
setup | Composition API entry (or use <script setup> in SFCs) |
DOM
templateis a template string that will replace the mounted elementrenderalternatively, define the template with a render functionelis not used oncreateApp: pass the selector toapp.mount('#app')instead
Assets
directiveslocal directivescomponentslocal components
Filters (filters option / Vue.filter) were removed in Vue 3. Use methods or computed properties instead.
Composition
mixinsan array of mixin objectsextendsextend another componentprovide/injectdependency injection
Other options
nameuseful in debugging and recursive componentsinheritAttrsdefaults to true; set false to stop non-prop attributes falling through to the root elementcompilerOptionsper-component compiler options
Instance properties
Given an instance (rarely needed with <script setup>; more common in Options API plugins and tests):
Properties
vm.$datathe data object associated to the instancevm.$propsthe props the instance has receivedvm.$elthe DOM element to which the instance is boundvm.$optionsthe object used to instantiate the Vue instancevm.$parentthe parent instancevm.$rootthe root instancevm.$slotsthe slots passed to the componentvm.$refsan object that contains a property for each element pointed by arefattributevm.$attrsattributes provided to the component but not defined as props
$children, $listeners, and $scopedSlots from Vue 2 are gone. Use $attrs for fallthrough listeners, and $slots for all slots.
Methods Data
vm.$watchset up a watcher for property changesvm.$emittrigger a custom event
$set / $delete are unnecessary in Vue 3 (Proxy reactivity). Prefer ref / reactive mutations.
Events
Prefer declaring emits and calling emit() from <script setup>, or this.$emit in Options API. The Vue 2 instance event bus APIs $on / $once / $off were removed. For app-wide events, use an external emitter or a store (Pinia; see my Vuex / state management notes for the older Vuex context).
Lifecycle Methods
vm.$forceUpdateforce the instance to re-rendervm.$nextTickschedule a callback for the next DOM update cycle
Mount and unmount go through the app instance: app.mount() / app.unmount().
Want me to talk about your product? You can sponsor this site.