반응형
VueJ: 컴포넌트에 생성하기 전에 계산된 속성이 계산됩니까?
다음과 같은 컴포넌트가 있습니다.
export default {
name: 'todos',
props: ['id'],
created () {
this.fetchData()
},
data() {
return {
}
},
computed: {
todos () {
return this.$store.state.todos[this.id]
}
},
methods: {
async fetchData () {
if (!this.$store.state.todos.hasOwnProperty(this.id)) {
await this.$store.dispatch('getToDos', this.id)
}
}
}
}
지금 일어나고 있는 일은 다음과 같습니다.
- 컴포넌트가 수신하는 것은
id소품을 통해서요.
컴포넌트가 로드될 때 ID를 기반으로 데이터를 가져와야 합니다.
나는 가지고 있다
created()내가 함수라고 부르는 곳에서 후크fetchData()데이터를 가져옵니다.메서드에서는
fetchData()함수는 데이터를 얻기 위한 액션을 디스패치합니다.그러면 데이터가 가져와 Vuex 저장소에 저장됩니다.계산된 속성
todos이 ID의 데이터를 가져옵니다.
문제는 페이지가 처음 로드될 때 계산된 속성이todos정의되지 않은 것으로 표시됩니다.페이지(클라이언트 측)를 변경하면 계산된 속성이 스토어에서 올바른 데이터를 가져와 표시합니다.
계산된 속성이 업데이트되지 않는 이유를 이해할 수 없습니다.
다음과 같은 방법을 사용할 수 있습니다.
component.vue(및 렌더링만)todoItem)
methods: {
async fetchData () {
const _this = this;
if (!this.$store.state.todos.hasOwnProperty(this.id)) {
this.$store.dispatch('getToDos', {id: this.id, callback: () => {
_this.todoItem = _this.$store.state.todos[_this.id]
}});
}
}
}
store.displaces를 설정합니다.
actions: {
getToDos: (context, payload) => {
// simulate fetching externally
setTimeout(() => {
context.commit("getToDos__", {newId: payload.id, task: "whatever" });
payload.callback();
}, 2000);
},
이 문제를 해결할 수 있는 것은 Getter를 만드는 것입니다.todos.
따라서 VueX 스토어에서 다음을 추가합니다.
getters: {
todos(state) {
return state.todos;
}
};
그리고 너의 것보다computed용도:
computed: {
todos () {
return this.$store.getters.todos[this.id]
}
}
언급URL : https://stackoverflow.com/questions/53006986/vuejs-computed-property-is-calculated-before-created-in-component
반응형
'source' 카테고리의 다른 글
| Vuex의 세 마침표 구문? (0) | 2022.08.27 |
|---|---|
| Linux에서의 데몬 로깅 (0) | 2022.08.27 |
| 정수 제수를 일정하게 사용하여 효율적인 부동 소수점 나눗셈 (0) | 2022.08.27 |
| bootstrap-vue: b-form-datepicker가 정지될 때까지 v-모델로 업데이트되지 않음 (0) | 2022.08.27 |
| 컴파일된 실행 파일에서 컴파일러 옵션을 가져오시겠습니까? (0) | 2022.08.27 |