<!-- 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>
我将代码分开以获取商店的状态,如下所示,并将其放在另一个文件中。
//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 };
像这样,我想把这段代码分开↓
const store = useStore();
const changeSelect = (e) => {
store.commit("resultColor/updateResultColor", {
type: props.selectType,
value: e.target.value,
});
};
我不想重复使用useStore。有解决办法吗?
可组合的use
函数应该直接在setup
函数中使用,或者在<script setup>
的情况下,在标记的顶层使用。在其他地方的使用取决于函数的实现,需要确认。
useStore
一般每组分使用一次:
import { useStore } from "vuex";
const store = useStore();
...
如果代码不在组件中,可以直接导入store:
import store from '...';
在这种情况下,这可能是XY问题,因为如果storeData
需要不断重构,这意味着存储设计不正确。state
包含的响应性对象可以是存储中的getter,因为它只涉及最新的存储数据。