Introduction
State management helps keep track of data that changes in your app. It makes sure all parts of your app see the same data and stay updated.
State management helps keep track of data that changes in your app. It makes sure all parts of your app see the same data and stay updated.
const state = reactive({ count: 0 }) function increment() { state.count++ }
reactive to create a shared state object in Vue 3 Composition API.import { reactive } from 'vue' const state = reactive({ message: 'Hello' }) function updateMessage(newMsg) { state.message = newMsg }
ref for a single reactive value like a counter.import { ref } from 'vue' const count = ref(0) function increment() { count.value++ }
This Vue component shows a counter using a shared reactive state. Clicking the button updates the count and the display changes automatically.
<template>
<div>
<p>Count: {{ state.count }}</p>
<button @click="increment">Add 1</button>
</div>
</template>
<script setup>
import { reactive } from 'vue'
const state = reactive({ count: 0 })
function increment() {
state.count++
}
</script>Without state management, components might have their own copies of data, causing confusion.
Vue's reactive and ref help keep data reactive and synced.
State management keeps your app data organized and consistent.
It helps multiple parts of your app share and update data easily.
Using Vue's reactive tools makes state management simple and effective.
State refers to the data that changes over time in your app.ref to create reactive primitive values like numbers.reactive on a primitive, which is incorrect. const count = state(0); uses a non-existent state function. const count = ref(0); correctly uses ref(0). const count = ref({ value: 0 }); creates a ref containing a plain object whose inner properties are not reactive.const state = reactive({ count: 0 });
function increment() {
state.count++;
}
increment();
console.log(state.count);state object is reactive with a count property starting at 0. The increment function increases count by 1.increment() increases state.count from 0 to 1. Then console.log(state.count) outputs 1.const state = reactive({ count: 0 });
function increment() {
state.count += 1;
}
export default { setup() { return { state, increment }; } }increment is called. What is the likely problem?state is reactive and increment correctly updates state.count.state.count in its template, Vue won't know to update the display when it changes.state.count in its template -> Option APass the test and this pattern moves unknown