여러 구성 요소가 Vuex에서 동일한 작업을 사용하여 데이터를 가져오는 경우 상태를 처리하는 방법은 무엇입니까?
저는 한동안 Vuex를 사용하여 전체 앱 상태를 제어하고 있습니다.하지만 지금 나는 전에 한 번도 만나보지 못한 문제에 직면해 있다.
워크플로우는 다음과 같습니다.
- 루트 구성 요소는 여러 개체가 포함된 배열인 내 데이터베이스에서 데이터를 가져옵니다.
- 하위 구성 요소를 생성하고 v-for를 사용하여 사용자에게 이 어레이를 표시합니다(즉, 각 하위 구성 요소는 나중에 어레이의 개체를 나타냅니다).
- 문제는 각 자식 컴포넌트의 비동기 데이터를 가져오려고 할 때 데이터 가져오기를 위해 앞서 설명한 어레이에서 가져온 파라미터도 필요합니다.
- 하위 구성 요소의 생성된 후크에서 Vuex 작업을 사용합니다.액션
fetch_sim_Type
는 payload(parent-component 및 초기 배열의 파라미터)를 가져옵니다.그리고 상태를 바꾸다simType
에서state: {}
Vuex의 것입니다. - 계산된 속성을 사용하여 가져온 정보를 가져올 수 있습니다.
simType
사용자에게 보여 줍니다.지금까지는 모든 것이 잘 된다.
코드:
초기 어레이(부모 컴포넌트의 simSumArray)는 다음과 같습니다.
[
{ typeid: 1, name: XXX },
{ typeid: 2, name: ZZZ },
{ typeid: 3, name: GGG },
{ typeid: 4, name: JJJ },
]
부모 컴포넌트:
<template
v-for="(singleSim, idx) in simSumArray"
>
<sim-single :singleSim="singleSim"></sim-single>
</template>
아이 컴포넌트:
props: ['singleSim'],
created () {
store.dispatch('fetch_sim_Type', this.singleSim.typeid);
},
computed: {
simType () {
console.log("store.getters.get_simType: ", store.getters.get_simType)
return store.getters.get_simType;
}
},
VUEX의 경우:
state: {
simType: 'unknown'
},
actions: {
fetch_sim_Type (context, typeid) {
//.. fetch the data based on typeid from DB
context.state.simType = fetchedData;
}
}
그러나 이 기능은 개체가 존재할 때만 어레이에 있을 때 작동합니다.여러 개의 하위 구성 요소가 생성되어 있는 경우.Vuex store.js의 상태 simType은 여러 번 교체되며 모든 자식 컴포넌트에서 simType()은 항상 동일합니다.
그 문제는 설명하기가 좀 어렵다.가장 큰 문제는 Vuex의 상태는 앱 전체에서 공유되도록 되어 있기 때문에 여러 개의 하위 컴포넌트가 있는 경우 공유 상태가 항상 대체되고 모든 하위 컴포넌트의 개별 상태를 가져올 수 없다는 것입니다.
내가 그 문제를 명쾌하게 설명할지는 모르겠지만 나는 정말 열심히 하려고 노력했다.Vuex 없이 데이터 가져오기 작업을 수행할 수 있는 더 좋은 방법이 있거나 Vuex를 잘못 사용한 것일 수 있습니다.
나는 이것이 어려운 질문이 아니라고 확신한다.하지만 온라인에서는 상대적인 답을 찾을 수 없어요.
코드를 읽어보면, 당신이 묘사한 행동은 정상입니다.고객님의 문제에 대한 두 가지 해결책이 있습니다(솔루션2가 원하는 것에 가까운 것 같습니다).
솔루션 1 - simType을 컴포넌트에 저장
컴포넌트 내부가 아닌 다른 곳에서 simType에 액세스하여 자신의 주에 저장해야 하는 경우 솔루션 2로 건너뜁니다.
구성 요소가 생성되면 구성 요소의 데이터에 simtype을 저장합니다.이것은 다음과 같습니다.
컴포넌트:
data () {
return {
simType: undefined //declare simType as one of your component's data property
}
},
created () {
store.dispatch('fetch_sim_Type', this.singleSim.typeid).then(simType => {
this.simType = simType //store the fetched simType
})
}
vuex 작업:
actions: {
fetch_sim_Type (context, typeid) {
//.. fetch the data based on typeid from DB
return fetchedData //pretty much the same except return the result
}
}
솔루션 2 - ID에 따라 색인화된 상태로 simType 저장
가져온 simType을 다음과 같이 ID별로 저장합니다.
state: {
simTypes: {} //simTypes is now plural, and is an empty object at first. It will later contain several simTypes, indexed by their respective Ids
},
actions: {
fetch_sim_Type (context, typeid) {
//.. fetch the data based on typeid from DB
context.state.simType[typeid] = fetchedData; // a fetched simtyped will be store in simTypes and can be accessed with the typeid as a key
}
}
simType을 검색하려면 다음과 같이 vuex getter를 쓸 수 있습니다.
getters: {
getSimTypeById: (state) => (typeId) => {
return state.simTypes[typeId]
}
}
따라서 이 예에서 계산된 방법은 다음과 같습니다.
computed: {
simType () {
console.log("store.getters.getSimTypeById(this.singleSim.typeid): ", store.getters.getSimTypeById(this.singleSim.typeid)
return store.getters.getSimTypeById(this.singleSim.typeid);
}
},
이 솔루션은 보너스로 여러 항목이 동일한 simType을 가지고 있는 경우에만 simType을 가져올 수 있습니다.
Vuex 스토어에 공유 데이터를 보관하고 컴포넌트에서 이를 감시함으로써 성공을 거두었습니다.
베스트 프랙티스는 아니지만, 상태를 바꾸기 위해 행동이나 커밋을 사용하지 않고 직접 상태를 수정하는 경우도 있습니다.시나리오에서는 Vuex처럼 합니다.data
모든 컴포넌트를 대상으로 합니다.
Vue 스토어
state: {
myvalue: []
}
구성 요소들
watch: {
'$store.state.myvalue'(value) {
}
}
언급URL : https://stackoverflow.com/questions/54332755/how-to-handle-the-state-when-multiple-components-use-the-same-actions-in-vuex-fo
'programing' 카테고리의 다른 글
IntelliJ Star(패키지) 비활성화수입품? (0) | 2022.08.30 |
---|---|
sprintf() 대신 asprintf()를 사용하는 이유는 무엇입니까? (0) | 2022.08.30 |
최종 정적 최종과 정적 최종의 차이 (0) | 2022.08.30 |
매핑된 getter가 정의되지 않았습니다. (0) | 2022.08.28 |
Vue.js 2.5+에서 Vuetify와 함께 Vue-IMASK를 사용하는 방법 (0) | 2022.08.28 |