반응형
Vuex에 디스패치된 작업 후 컴포넌트에 데이터를 전달하는 방법
Vuex를 사용하여 애플리케이션 수준의 데이터를 관리하려고 합니다.나는 악리를 사용하여 데이터를 가져와 컴포넌트 내의 데이터 변수에 데이터를 전달합니다.복잡한 건 없어요.
저희 가게는 이렇게 생겼어요.
// store.js
// appropriate imports and such
export const store = new Vuex.Store({
state: {
var: []
},
actions:{
getData(context){
axios.get('/endpoint').then(function(response){
context.state.var = res.data.value1;
console.log("action in store.js run");
//appropriate brackets,etc below
그런 다음 이 액션을 앱으로 디스패치합니다.js
//appropriate imports and such above
const app = new Vue({
el: '#app',
store: store,
created() {
this.$store.dispatch('getRightSidebar')
console.log("action dispatched")
}
});
작성한 라이프 사이클 훅을 사용하여 컴포넌트를 마운트하기 전에 이 액션을 디스패치합니다.이 시점에서 2개의 메시지가 콘솔에 기록됩니다.작성된 라이프스타일훅 메시지와 디스패치 중인 실제 액션 메시지 중 하나.그러나 응용 프로그램을 실행하면 이전 메시지만 기록됩니다.물론 액션이 디스패치되면 실제 메서드/요구는 호출/실행됩니다.
상태 변수 값을 인쇄하면 컴포넌트의 마운트된 라이프 사이클 후크 내에서 정의되지 않습니다.그러나 상태를 인쇄하면 해당 데이터가 포함된 객체가 기록됩니다.
///component.js
mounted() {
console.log("component mounted")
console.log(this.$store.state.var) // undefined
console.log(this.$store.state) // Obeject with the appropriate data
}
따라서 한편으로는 액션을 디스패치하는 것처럼 보이지만 상태로부터 개별 객체에 액세스하려고 하면 자동으로 크래핑됩니다.주(州) 내의 개체에 액세스하는 방법에 문제가 있습니까?
'기다려라'가 필요합니다.getData
해결을 약속하다
created() 훅 실행 시 데이터는 사용할 수 없습니다.
export const store = new Vuex.Store({
state: {
var: []
},
actions:{
getRightSidebar(context){
// must return Promise to subscribe to it!
return axios.get('/endpoint').then(function(response){
context.state.var = res.data.value1;
console.log("action in store.js run");
const app = new Vue({
el: '#app',
store: store,
data: {
isLoading: true
},
async mounted() {
await this.$store.dispatch('getRightSidebar')
// after this there is gonna be some data
this.isLoading = false
}
})
<template>
<div>
<div v-if='isLoading'>loading...</div>
<div v-else>{{$store.state.yourvariable}}</div>
</div>
</template>
언급URL : https://stackoverflow.com/questions/63509077/how-to-pass-data-to-component-after-action-dispatched-to-vuex
반응형
'programing' 카테고리의 다른 글
문자열을 한 줄씩 읽다 (0) | 2022.08.17 |
---|---|
C에서 true와 false 사용 (0) | 2022.08.17 |
어떻게 C의 printf의%(%)표시에서 벗어나려는 (0) | 2022.08.17 |
포인터를 거부하는 배열 크기 매크로 (0) | 2022.08.17 |
Ionic Vue 체크박스 (0) | 2022.08.17 |