Vue.js Directives Cheat Sheet

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. used in form elements, updates the model when the user changes the form field value
v-onceapplies the property just once, and never refreshes it even if the data passed changes

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' }}

VueJS 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.

VueJS Global Configuration of the Vue object

The Vue.config object has these properties, which you can modify when you create the instance:

PropertyDescription
silentdefaults to false, if true suppress logs and warnings
optionMergeStrategiesallows to define a custom merging strategy for options
devtoolsdefaults to true in development, and false in production. You can override those values.
errorHandlerallows to set an error handler function. Useful to hook Sentry and other similar services
warnHandlerallows to set a warning handler function, similar to errorHandler, but for warnings instead of errors
ignoredElementsused to let Vue ignore custom elements defined outside of it, like Web Components.
keyCodeslet you define custom key aliases for v-on
performancedefaults to false. If set to true, traces the performance of Vue components in the Browser DevTools.
productionTipdefaults to true. Set to false to disable the warning “you’re in development mode” during development in the console.

DOM

elsets the DOM element where the instance mounts on. It can be a CSS Selector, or an HTMLElement
templateis a template, represented as a string, that will replace the mounted element
renderalternatively, to define the template, you can define a template using a render function
renderErrorset an alternative output when the function attached to render fails

Vue instance assets

directivesthe set of directives to associate to the Vue instance
filtersthe set of filters to associate to the Vue instance
componentsthe set of components to associate to the Vue instance

Vue composition options

parentspecifies the parent instance
mixinssets an array of mixin objects
extendsextend another component

Other Vue object options

namesetting a name to the component lets you invoke it, useful in debugging or when you need to recursively add a component in its template
functionalif true, sets the component to be stateless (no data) and instances (no this), making it more lightweight
modelallows customizing the property used in events, useful for example when interacting with forms
commentsdefaults to false. If set to true, retains the HTML comments that are put in templates

Vue JS Instance properties

Given an instance of Vue, stored into a variable const vm = new Vue(/*...*/), you can inspect and interact with it.

Properties of a Vue instance

vm.$datathe data object associated to the instance
vm.$propsthe props the instance has received
vm.$elthe DOM element to which the instance is bound
vm.$optionsthe object used to instantiate the Vue instance
vm.$parentthe parent instance
vm.$rootthe root instance (if this is the root instance, this points to itself)
vm.$childrenan array of children instances
vm.$slotsan array of the associated slots contained in the template
vm.$scopedSlotsan array of the associated scoped slots
vm.$refsan object that contains a property for each element pointed by a ref attribute defined in the template
vm.$isServertrue if the Vue instance is running on the server (useful in server-side rendering)
vm.$attrsan object of attributes that are provided to the component but not defined as props
vm.$listeners an object of v-on event listeners assigned to the component

Vue JS Mouse event modifiers

v-on:click .lefttriggers only on left mouse button click
v-on:click .righttriggers only on right mouse button click
v-on:click .middletriggers only on middle mouse button click

Vue JS Modifying events

v-on:click.native trigger a native DOM event instead of a Vue event
v-on:click.stopstop the click event propagation
v-on:click.passive makes use of the passive option of addEventListener
v-on:click.capture use event capturing instead of event bubbling
v-on:click.self make sure the click event was not bubbled from a child event, but directly happened on that element
v-on:click.once the event will only be triggered exactly once
v-on:submit.preventcall event.preventDefault() on the triggered submit event, used to avoid a form submit to reload the page

Vue JS 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 .prop bind a prop instead of an attribute
v-bind .cameluse camelCase for the attribute name
v-bind .synca syntactic sugar that expands into a v-on handler for updating the bound value. See this.

Vue Built-in components

Vue provides 5 built-in components:

  • <component>
  • <transition>
  • <transition-group>
  • <keep-alive>
  • <slot>

Vue JS Options passed to a Vue object

When initializing a Vue object, you pass in an object:

const vm = new Vue({

})

This object accepts a number of properties.

PropertyDescription
dataallows to pass a set of reactive data that will be used by the Vue app. All reactive properties must be added at initialization time, you can’t add new ones later.
propsit’s a set of attributes that are exposed to parent components as input data.
propsDatadefault data for props. Only useful during testing
methodsa set of methods that are defined on the Vue instance
computedlike methods, but cached internally
watchallows to watch properties, and call a function when they change

Example of defining data, methods and computed properties:

var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  methods: {
    reverseMessageAsMethod: function () {
      return this.message.split('').reverse().join('')
    }
  },
  computed: {
    // a computed getter
    reversedMessage: function () {
      // `this` points to the vm instance
      return this.message.split('').reverse().join('')
    }
  }
})

console.log(vm.reverseMessageAsMethod) // => 'olleH'
vm.message = 'Goodbye'
console.log(vm.reversedMessage) // => 'eybdooG'

Methods Data

vm.$watchset up a watcher for property changes in the Vue data. It can also watch for value changes inside objects
vm.$setset a property
vm.$deletedelete a property

Events

vm.$emittriggers a custom event on the vm Vue instance
vm.$onlisten for a custom event on the vm Vue instance
vm.$oncelike $on, but listens only once
vm.$offremoves an event listener from the Vue instance

Lifecycle Methods

vm.$mountmount a Vue instance on a DOM element, in case it was not mounted yet
vm.$forceUpdateforce the vm Vue instance to re-render. Does not force child components to rerender.
vm.$nextTickaccepts a callback and schedules that for the next DOM update cycle
vm.$destroydestroys the application and remove all child components, observers and listeners

Vue JS Methods of the Vue object

MethodDescription
Vue.extendallows to subclass the Vue object, to create a custom profile
Vue.nextTickdefers the callback to be executed after the next DOM update cycle
Vue.setadd a property to the object
Vue.deletedelete a property from the object
Vue.directiveset (or get) a global directive
Vue.filterset (or get) a global filter
Vue.componentset (or get) a global component
Vue.useinstall a Vue.js plugin
Vue.mixinset a global mixin
Vue.compilecompile a template string into a render function
Vue.versionreturns the currently installed version of Vue

Vue Lifecycle Hooks

beforeCreatecalled before the app is created
createdcalled after the app is created
beforeMountcalled before the app is mounted on the DOM
mountedcalled after the app is mounted on the DOM
beforeDestroycalled before the app is destroyed
destroyedcalled after the app is destroyed
beforeUpdatecalled before a property is updated
updatedcalled after a property is updated
activatedcalled when a kept-alive component is activated
deactivatedcalled when a kept-alive component is deactivated