Akar provides flexible state management for components, allowing developers to use either controlled or uncontrolled state. Understanding when to use each approach ensures better integration with Vue's reactivity system.
A controlled component receives its state as a prop and requires explicit updates via event listeners. The parent component manages and synchronizes the state.
ASwitchRoot<script setup>
import { ASwitchRoot, ASwitchThumb } from 'akar';
import { ref } from 'vue';
const isActive = ref(false);
function handleUpdate(value) {
isActive.value = value;
}
</script>
<template>
<ASwitchRoot
:model-value="isActive"
@update:model-value="handleUpdate"
>
<ASwitchThumb />
</ASwitchRoot>
</template>
How it works:
ASwitchRoot component’s state is managed by the isActive ref.@update:modelValue event ensures updates propagate correctly.Vue’s v-model syntax provides a convenient way to bind values to controlled components in Akar. It automatically handles passing the value and listening for updates.
Example: Using v-model with ASwitchRoot
<script setup>
import { ASwitchRoot, ASwitchThumb } from 'akar';
import { ref } from 'vue';
const isActive = ref(false);
</script>
<template>
<ASwitchRoot v-model="isActive">
<ASwitchThumb />
</ASwitchRoot>
</template>
An uncontrolled component manages its own state internally, without requiring a parent-controlled prop. Instead of modelValue, Akar components use defaultValue to initialize state.
ASwitchRoot<template>
<ASwitchRoot default-value="true">
<ASwitchThumb />
</ASwitchRoot>
</template>
How it works:
ASwitchRoot initializes its state with defaultValue.@update:modelValue<!-- ❌ Incorrect: -->
<ASwitchRoot :modelValue="isActive" />
<!-- ✅ Correct: -->
<ASwitchRoot :modelValue="isActive" @update:modelValue="(val) => isActive = val" />
modelValue Instead of defaultValue<!-- ❌ Incorrect: -->
<ASwitchRoot :modelValue="true" />
<!-- ✅ Correct: -->
<ASwitchRoot defaultValue="true" />
// ❌ Incorrect:
const isActive = computed(() => store.state.toggleState);
// ✅ Correct:
const isActive = computed({
get: () => store.state.toggleState,
set: (val) => store.commit('setToggleState', val)
});