Trying to wrap my head around reactivity when it comes to states from a Pinia store.
I have the following store (@/stores/settings.js):
import { defineStore } from 'pinia'
export const useSettings = defineStore('Settings', {
state: () => ({
useDarkTheme: false
}),
persist: true
})
And the following component (App.vue):
<script setup>
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useSettings } from '@/stores/settings'
const settings = useSettings()
const { useDarkTheme } = storeToRefs(settings)
let appClasses = ref({
'test-class': true,
'dark-theme': useDarkTheme.value
})
</script>
<template>
<div class="app-wrapper" :class="appClasses">
<div class="app-content" :class="useDarkTheme ? 'đark' : 'light'">
/* ... */
</div>
</div>
</template>
On the app-content
div, useDarkTheme
is reactive: whenever its value changes in the store, the class switches betwenn "light" and "dark". No need to reload the app.
However when used in the appClasses
object, useDarkTheme
seems to loose its reativity. The "dark-theme" class is applied (or not) based on the value stored in Pinia when the component is loaded, but then it isn't updated to reflect the change that occurs in the store (until the component is loaded again, e.g. by reloading the app). The same is true if I use "reactive" instead of "ref".
What am I missing here?
Turns out I should have used useDarkTheme
instead of useDarkTheme.value
in my object:
let appClasses = ref({
'test-class': true,
'dark-theme': useDarkTheme
})
Thanks to @chiliNUT for the tip!