![](/img/trans.png)
[英]How do I get multiple actions and state with Vuex namespaced modules and the Vue Composition API?
[英]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>
我分離代碼以獲取商店的 state,如下所示,並將其放在不同的文件中。
//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
function 中使用,或者在<script setup>
的情況下,在標簽的頂層。 其他地方的使用依賴function實現,需要確認。
useStore
通常每個組件使用一次:
import { useStore } from "vuex";
const store = useStore();
...
如果代碼不在組件內,可以直接導入商店:
import store from '...';
在這種情況下,這可能是 XY 問題,因為如果storeData
需要不斷地重新構建,這意味着存儲設計不正確。 state
包含的 Reactive object 可能是商店內部的吸氣劑,因為它只涉及最新的商店數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.