Reactive Data

View saved

ref for simple values

Wrap primitives (and often objects) in ref. In script, use .value; templates unwrap automatically.

<script setup>
import { ref } from "vue";

const count = ref(0);

function increment() {
  count.value += 1;
}
</script>

<template>
  <button type="button" @click="increment">Count: {{ count }}</button>
</template>

reactive for objects

reactive makes an object's properties reactive.

import { reactive } from "vue";

const form = reactive({
  name: "",
  email: "",
});

When to choose which

  • Prefer ref for numbers, strings, booleans, and most component state
  • Use reactive for groups of related fields
  • Reassigning a whole reactive object loses reactivity—mutate properties or use ref

State drives the template

Change state in methods or event handlers; Vue re-renders the affected DOM.

Comments

One comment per signed-in account. Comments are saved with this page’s URL.