반응형
rest api에서 데이터를 가져오기 위해 vuex 저장소를 처리하는 방법
애플리케이션 상태를 처리하기 위해 Vuex를 사용하고 있습니다.
rest api에 Ajax Get 요청을 한 후 오브젝트 목록을 표시해야 합니다.
서버에서 이 데이터를 로드하는 액션을 디스패치하고 있는데 컴포넌트에서 처리하는 방법을 모르겠습니다.
이제 이런 게 있어요.
//component.js
created(){
this.$store.dispatch("fetch").then(() => {
this.objs = this.$store.state.objs;
})
}
그러나 로컬 자산에 수신 데이터를 할당하는 것은 스토어 데이터를 처리하는 올바른 방법이 아니라고 생각합니다.
이 문제를 더 잘 해결할 방법은 없을까?mapState를 사용하시겠습니까?
감사합니다!
방법은 여러 가지가 있지만, 자신의 접근법에 맞는 것을 스스로 실험하고 찾아내야 합니다.이것이 내가 제안하는 것이다.
{ // the store
state: {
something: ''
},
mutations: {
setSomething (state, something) {
// example of modifying before storing
state.something = String(something)
}
},
actions: {
fetchSomething (store) {
return fetch('/api/something')
.then(data => {
store.commit('setSomething', data.something)
return store.state.something
})
})
}
}
}
{ // your component
created () {
this.$store
.dispatch('fetchSomething')
.then(something => {
this.something = something
})
.catch(error => {
// you got an error!
})
}
}
상세한 것에 대하여는, https://vuex.vuejs.org/en/actions.html 를 참조해 주세요.
이제 작업 자체의 오류를 처리하고 있다면 작업을 호출하고 스토어의 값을 참조하는 계산된 속성을 사용할 수 있습니다.
{
computed: {
something () { // gets updated automatically
return this.$store.state.something
}
},
created () {
this.$store.dispatch('loadSomething')
}
}
언급URL : https://stackoverflow.com/questions/50382622/how-to-handle-vuex-store-to-fetch-data-from-rest-api
반응형
'programing' 카테고리의 다른 글
Vuetify 드롭다운 높이 감소 (0) | 2022.08.15 |
---|---|
Vue를 사용하여 스택 크기를 초과한 비동기 함수 (0) | 2022.08.15 |
C로 base64 부호화(디코딩)하려면 어떻게 해야 하나요? (0) | 2022.08.15 |
자바 객체 대 객체 매핑을 위한 툴이 있습니까? (0) | 2022.08.15 |
"text"와 새로운 String("text")의 차이점은 무엇입니까? (0) | 2022.08.15 |