Reactivity Fundamental
Vue’s reactivity system automatically keeps your UI in sync with your data. This section covers how to declare reactive state, use refs and reactive objects, and best practices for managing state in Vue components.
Declaring Reactive State
Section titled “Declaring Reactive State”Using ref()
Section titled “Using ref()”The recommended way to declare reactive state in the Composition API is with the ref() function:
import { ref } from 'vue'const count = ref(0)ref() returns a reactive object with a .value property. In templates, refs are automatically unwrapped:
// Example Vue SFC (for illustration only)// <template>// <button @click="count++">{{ count }}</button>// </template>// <script setup>import { ref } from 'vue'const count = ref(0)// </script>Using reactive()
Section titled “Using reactive()”For objects, use reactive() to make the entire object reactive:
import { reactive } from 'vue'const state = reactive({ count: 0 })In templates:
<button @click="state.count++">{{ state.count }}</button>Why Use Refs and Reactive?
Section titled “Why Use Refs and Reactive?”Refs and reactive objects allow Vue to track dependencies and update the DOM efficiently. Use refs for primitives and reactive for objects/arrays.
Deep Reactivity
Section titled “Deep Reactivity”Reactive objects are deeply reactive, so nested properties are tracked:
const obj = ref({ nested: { count: 0 } })obj.value.nested.count++DOM Update Timing
Section titled “DOM Update Timing”DOM updates are batched and applied asynchronously. Use nextTick() to wait for the DOM update:
import { nextTick } from 'vue'await nextTick()Best Practices
Section titled “Best Practices”- Use
ref()for primitives,reactive()for objects. - Avoid destructuring reactive objects to keep reactivity.
- Use composables to share stateful logic.