'When using Vue3 composition api and vuex together, how can I separate the function that changes state?
<!-- SelectColor.vue -->
<script setup>
import { defineProps } from "vue";
import { useStore } from "vuex";
import { storeData } from "./common";
let { resultColor } = storeData();
const props = defineProps({
selectType: String,
});
const store = useStore();
const changeSelect = (e) => {
store.commit("resultColor/updateResultColor", {
type: props.selectType,
value: e.target.value,
});
};
const selectedOption = (type) => {
return props.selectType == type;
};
</script>
I separated the code to get the state of the store as below and put it in a different file.
//common.js
import { computed, reactive, toRefs } from "vue";
import { useStore } from "vuex";
const storeData = () => {
const store = useStore();
let state = reactive({
count: computed(() => store.state.count.count),
resultColor: computed(() => store.state.resultColor.resultColor),
resultList: computed(() => store.state.count.result),
});
return toRefs(state);
};
export { storeData };
Like this, I want to separate this code.↓
const store = useStore();
const changeSelect = (e) => {
store.commit("resultColor/updateResultColor", {
type: props.selectType,
value: e.target.value,
});
};
I don't want to use the useStore repeatedly. Is there a solution to this?
Solution 1:[1]
Composable use functions are supposed to be used directly in setup function, or in the case of <script setup>, at the top level of the tag. The usage in other places depends on function implementation and needs to be confirmed.
useStore is generally used once per component:
import { useStore } from "vuex";
const store = useStore();
...
In case the code doesn't reside inside a component, a store can be imported directly:
import store from '...';
In this case this can be XY problem because if storeData needs to be constantly restuctured, this means that the store was incorrectly designed. Reactive object that state contains could be a getter inside the store, because it only involves up-to-date store data.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
