The correct syntax for defining a ref in Vue 3 Composition API:
import { ref } from 'vue'
const count = ref(0)
Key points:
- Import:
import { ref } from 'vue' - Create:
const variableName = ref(initialValue) - Access in JavaScript: Use
.valueproperty →count.value - Access in template: Refs are automatically unwrapped →
{{ count }}(no.valueneeded)
Type signature:
function ref<T>(value: T): Ref<UnwrapRef<T>>
Complete example:
<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value++ // Use .value in JavaScript
}
</script>
<template>
<button @click="increment">
{{ count }} <!-- No .value needed in template -->
</button>
</template>
Important characteristics:
- The ref object is mutable and reactive
- Mutating
.valuetriggers reactive updates - Objects assigned to refs are deeply reactive (use
shallowRef()to avoid) - Nested refs are automatically unwrapped
Sources: