The Vue.js Cheat Sheet

By

A Vue.js 3 cheat sheet covering directives, form bindings, event modifiers, lifecycle hooks, createApp, and the options you use day to day.

~~~

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.

DirectiveDescription
v-textuses the property as the text value of the element
v-htmluses the property as the text value of the element, interpreting HTML
v-ifshow an element only if the conditional is true
v-elseshows an alternative element if the preceding v-if is false
v-else-ifadds an else if block for a v-if construct
v-showsimilar to v-if, but adds the element to the DOM even if falsy. Just sets it to display: none.
v-foriterates over an array or iterable object
v-onlisten to DOM events
v-bindreactively update an HTML attribute
v-modelsets up a two-way binding for form inputs (and components via modelValue)
v-slotdeclare a named or scoped slot (# shorthand)
v-preskip compilation for this element and its children
v-onceapplies the property just once, and never refreshes it even if the data passed changes
v-memomemoize a subtree; only re-render when a dependency in the array changes
v-cloakhidden 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

.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

Submit an event only if a particular key is pressed

Keyboard event modifiers

Only trigger the event if a particular keyboard key is also pressed:

v-bind

.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):

Built-in components and special elements

Vue provides these built-in components and special template elements (<component> and <slot> are special elements, not components):

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.

APIDescription
createAppcreate an application instance
nextTickdefer the callback until after the next DOM update cycle
defineComponenttype helper for component options
defineAsyncComponentlazy-load a component
hcreate a VNode (hyperscript)
ref / reactive / computed / watch / watchEffectComposition API reactivity
provide / injectdependency injection
onMounted and other on* helpersComposition API lifecycle

App instance methods:

MethodDescription
app.componentregister or retrieve a global component
app.directiveregister or retrieve a global directive
app.useinstall a plugin
app.mixinapply a global mixin (use sparingly)
app.provideprovide a value to all descendants
app.mountmount the app on a DOM element
app.unmountunmount the app
app.configapp-level configuration object

App config

app.config has these properties:

PropertyDescription
errorHandlerset an error handler function. Useful to hook Sentry and other similar services
warnHandlerset a warning handler function, similar to errorHandler, but for warnings
globalPropertiesadd properties available on every component instance (this.foo in Options API)
optionMergeStrategiescustom merge strategies for options
performanceif true, traces component performance in Browser DevTools
compilerOptionsruntime 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.

PropertyDescription
dataa function that returns reactive state. Must be a function so each instance gets its own object
propsattributes exposed to parent components as input data
emitsdeclare events the component can emit
methodsmethods defined on the instance
computedlike methods, but cached internally
watchwatch properties, and call a function when they change
setupComposition API entry (or use <script setup> in SFCs)

DOM

Assets

Filters (filters option / Vue.filter) were removed in Vue 3. Use methods or computed properties instead.

Composition

Other options

Instance properties

Given an instance (rarely needed with <script setup>; more common in Options API plugins and tests):

Properties

$children, $listeners, and $scopedSlots from Vue 2 are gone. Use $attrs for fallthrough listeners, and $slots for all slots.

Methods Data

$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

Mount and unmount go through the app instance: app.mount() / app.unmount().

Tagged: Vue.js · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about vue: