Skip to main content

Vue Essentials

Template syntax

Template syntax

computed

A computed property will only re-evaluate when some of its reactive dependencies have changed. Avoid mutating computed value

v-if vs v-show

Generally speaking, v-if has higher toggle costs while v-show has higher initial render costs. So prefer v-show if you need to toggle something very often, and prefer v-if if the condition is unlikely to change at runtime.

Component props

kebab-case instead of camelCase. Because HTML tags and attribute names are case-insensitive.

@change vs @input

@input (fires when user changes input value) instead of @change (fires when user changed value and unfocus input, e.g. click somewhere outside)

v-bind (:) vs v-model

One-way binding vs Two-way binding

watch vs watchEffect

  • watch only trigger the callback when the 1st argument changes -> more precise control over when the callback should fire.
  • watchEffect automatically track when any reactive dependency changes and re-run the effect -> more concise but makes its reactive dependencies less explicit.
<script setup>
import { ref, watch } from 'vue'

const todoId = ref(1)
const data = ref(null)

watch(todoId, async () => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/todos/${todoId.value}`
)
data.value = await response.json()
}, { immediate: true })
</script>