TechSchool
Home / Cheat sheets / Vue 3

Vue 3 cheat sheet

96 one-line examples for Vue 3. Open it while you code, or print it and keep it near the keyboard. Free, with no signup and no ads.

Template Syntax

CodeWhat it does
{{ message }}Show a value as text.
<div v-text="msg"></div>Set text content from a value.
<p v-html="raw"></p>Insert HTML markup from a value.
<img :src="url">Bind an attribute to a value.
<button :disabled="busy">Toggle an attribute with a boolean.
<a :href="'/u/' + id">Build an attribute with an expression.
<input v-model="name">Link an input to a value.
<input v-model.number="age">Store the input as a number.
<input v-model.trim="text">Remove spaces from both ends.
<div v-bind="attrs"></div>Bind many attributes from one object.
<p>{{ ok ? 'Yes' : 'No' }}</p>Show one of two texts.
<p>{{ price.toFixed(2) }}</p>Call a method inside the template.

Directives and Events

CodeWhat it does
<p v-if="seen">Hi</p>Add the element only when true.
<p v-else>Hidden</p>Show this element when v-if is false.
<p v-show="seen">Hi</p>Hide the element with CSS only.
<li v-for="item in list">Repeat the element for each item.
<li v-for="(item, i) in list">Repeat and get the index too.
<li v-for="item in list" :key="item.id">Repeat with a stable key.
<button @click="count++">Run code when the user clicks.
<button @click="save">Call a method on click.
<form @submit.prevent="send">Stop the default form submit.
<input @keyup.enter="go">Run code when Enter is pressed.
<div @click.stop="pick">Stop the click from bubbling up.
<button @click.once="init">Run the handler only one time.

Reactivity and State

CodeWhat it does
import { ref } from 'vue'Import the ref function.
const count = ref(0)Create a reactive number.
count.value++Change a ref value in script.
const user = reactive({ name: '' })Create a reactive object.
user.name = 'Ana'Change a reactive object property.
const total = computed(() => a.value + b.value)Create a value from other values.
watch(count, (v) => console.log(v))Run code when a value changes.
watchEffect(() => console.log(count.value))Track used values and run again.
const { count } = toRefs(state)Turn object properties into refs.
const state = ref({ n: 1 })Store an object inside a ref.
state.value.n = 2Change a nested value in a ref.
const name = ref('')Create a ref for a text input.

Components

CodeWhat it does
import Card from './Card.vue'Import a child component.
<Card />Use the imported component.
<Card title="Hello" />Pass a static text prop.
<Card :count="total" />Pass a value as a prop.
defineProps(['title'])Declare the props a component takes.
defineProps({ title: String })Declare a prop with a type.
const emit = defineEmits(['save'])Declare the events a component sends.
emit('save', data)Send an event to the parent.
<slot />Show content passed by the parent.
<slot name="head" />Show a named slot.
<template #head>Title</template>Fill a named slot.
<Card v-bind="props" />Pass all props from one object.

Lifecycle Hooks

CodeWhat it does
import { onMounted } from 'vue'Import the mounted hook.
onMounted(() => load())Run code after the component mounts.
onUnmounted(() => stop())Run cleanup code after unmount.
onUpdated(() => sync())Run code after an update.
onBeforeMount(() => init())Run code before the mount.
onBeforeUnmount(() => save())Run code before the unmount.
onMounted(() => { timer = setInterval(tick, 1000) })Start a timer after mount.
onUnmounted(() => clearInterval(timer))Clear the timer on unmount.
onActivated(() => refresh())Run code when a kept view shows.
onDeactivated(() => pause())Run code when a kept view hides.
onErrorCaptured((e) => log(e))Handle errors from child components.
onMounted(async () => await load())Run async code after mount.

Composables

CodeWhat it does
export function useCount() {Start a reusable logic function.
const count = ref(0)Keep state inside the composable.
function inc() { count.value++ }Add a method to the composable.
return { count, inc }Return the state and methods.
import { useCount } from './useCount'Import the composable.
const { count, inc } = useCount()Use the composable in a component.
export function useFetch(url) {Start a data loading composable.
const data = ref(null)Hold the loaded data.
onMounted(async () => { data.value = await get(url) })Load data when the component mounts.
return { data }Return the loaded data.
const { data } = useFetch('/api/items')Load items with the composable.
export function useToggle(v = false) {Start a true and false helper.

Router

CodeWhat it does
import { createRouter, createWebHistory } from 'vue-router'Import the router tools.
const router = createRouter({ history: createWebHistory(), routes })Create the router with history mode.
const routes = [{ path: '/', component: Home }]Define one route.
app.use(router)Add the router to the app.
<RouterView />Show the matched route component.
<RouterLink to="/about">About</RouterLink>Make a link to a route.
<RouterLink :to="{ name: 'user', params: { id } }">Link to a named route with a param.
const route = useRoute()Get the current route object.
route.params.idRead a route parameter.
const router = useRouter()Get the router object.
router.push('/home')Go to another route.
router.back()Go back to the last route.

Pinia Store

CodeWhat it does
import { createPinia } from 'pinia'Import the store tool.
app.use(createPinia())Add the store to the app.
import { defineStore } from 'pinia'Import the store helper.
export const useUser = defineStore('user', {Define a store with a name.
state: () => ({ name: '' }),Set the first state values.
getters: { upper: (s) => s.name.toUpperCase() },Add a value from state.
actions: { setName(n) { this.name = n } },Add a method to change state.
const store = useUser()Use the store in a component.
store.name = 'Ana'Change a state value directly.
store.setName('Ana')Call a store action.
store.$reset()Reset the store to first values.
const { name } = storeToRefs(store)Keep store state reactive after unpack.
More on TechSchool
See the Vue 3 interview questions Python JavaScript TypeScript HTML CSS React Node.js Java PHP C C++ C# Go SQL MongoDB Redis Linux Git Docker Data Structures