Can I use computed
inside a Pinia store?
#1765
Answered
by
posva
rodrigocfd
asked this question in
Help and Questions
-
When I need a computed value from the store, can I use Example: import {computed, reactive} from 'vue';
import {defineStore} from 'pinia';
const useFoo = defineStore('foo', () => {
const state = reactive({
name: 'Joe',
age: 41,
});
const prefixed = computed(() => `Mr. ${state.name}`);
const withAge = computed(() => `${state.name}, ${state.age}`);
function setName(name: string): void {
state.name = name;
}
return {prefixed, withAge, setName};
}); If this approach is not correct, how could I write it? |
Beta Was this translation helpful? Give feedback.
Answered by
posva
Oct 30, 2022
Replies: 1 comment 1 reply
-
Yes, that's exactly how to define a getter note you also need to return the state for it be picked up by devtools and, more importantly, for SSR: return {
...toRefs(state),
prefixed,
withAge,
// you don't need a setName action if it just sets the name
} Also worth seeing: https://pinia.vuejs.org/core-concepts/state.html#resetting-the-state |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
posva
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, that's exactly how to define a getter
note you also need to return the state for it be picked up by devtools and, more importantly, for SSR:
Also worth seeing: https://pinia.vuejs.org/core-concepts/state.html#resetting-the-state