programing

Vue2 + Vuex - 저장소에서 성공적으로 설정된 어레이를 렌더링하지 않음

yoursource 2022. 7. 17. 11:17
반응형

Vue2 + Vuex - 저장소에서 성공적으로 설정된 어레이를 렌더링하지 않음

209,579개의 옵션을 렌더링하려고 하는데 Vuex 라이프 사이클+액시스를 올바르게 사용하고 있지 않은 것 같습니다.

  • 콘솔에서 Vuex를 통해 스토어 상태로 설정된 모든 옵션이 표시됩니다.
  • 에러는 표시되지 않는다.
  • 옵션이 비어 있고 상태를 렌더링하지 않습니다.cityNames배열
  • main.js스토어를 모든 컴포넌트로 내보냅니다.

이 라이프 사이클을 제대로 적용하지 못한 것 같습니다.게터를 사용해야 하는데, 누군가가 라이프 사이클에 질서를 가져다 줄 수 있을까요?

store.displaces를 설정합니다.

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);

export default new Vuex.Store({
state: {
        isTrue: true,
        cityNames: [],
    },

    getters:{
        getCityNames(state){
            return state.cityNames;
        }
    },
    mutations: {
        SetCityNames(state, cityNames){
            state.cityNames = cityNames
    },
    actions: {
        loadData({commit}){
            axios.get('http://localhost:3000/allCities')
                .then(function (response) {
                    commit('SetCityNames', response.data)
                }).catch(function (error) {
                    console.log(error);
            });

        }
    },
});

대본

export default {
    name: "Weather",
    methods: {
        allCityNames() {
            this.$store.dispatch('loadData')
        }
    },
    created() {
        this.allCityNames();
    }
}

템플릿

<select>
    <option disabled value="">Please select one</option>
    <option v-for="cityName in $store.cityNames">{{cityName}}</option>
</select>

고마워, 버드

컴퓨팅에서 실행되도록 코드를 변경했지만 (드디어) 다음과 같은 오류를 발견했습니다.maximum stacksize exceeded이 시점에서 Vue는 이러한 대규모 어레이(209,579개 항목)를 표시할 수 없다는 것을 알았습니다.

파트 I - 코드 변경:

다음과 같이 설정된 isLoaded 상태를 만들었습니다.true일단 공리들이 반응을 보이면

Axios 호출의 비동기 특성으로 인해 이 방법이 최선인지 아직 잘 모르겠습니다.이 방법은 다음과 같이 끝나지 않았을 수 있습니다.commit('SetCityNames', response.data);커밋을 호출한 직후에, 다음의 커밋이 호출됩니다.commit('changeLoadedState');

상태를 추가했습니다.isLoaded: false

getter가 추가되었습니다.didItLoad(state){return state.isLoaded}

변환이 추가되었습니다.changeLoadedState(state){state.isLoaded = true}

커밋 추가(commit('changeLoadedState');)는 나의 공리에게 행동을 호소한다.

loadData({commit}) {
            axios.get('http://localhost:3000/allCities')
                .then(function (response) {
                    commit('SetCityNames', response.data);
                    commit('changeLoadedState');
                }).catch(function (error) {
                console.log(error);
            });
        }

내 컴포넌트에서는 아직 Axios call in 메서드를 디스패치하고 있습니다.처음 호출된 Axios call in 메서드가 추가되어 있기 때문입니다.computed렌더 측의 메서드는 다음과 같습니다.

computed:{
          isLoaded(){
              return this.$store.getters.didItLoad;
          },
            renderCities(){
                return this.$store.getters.getCityNames;

            }
        }

렌더링된 내 템플릿에서 먼저 로드 상태를 선택한 후 다음 옵션을 채웁니다.

<select v-if="isLoaded">
    <option disabled value="">Please select one</option>
    <option v-for="cityName in renderCities">{{cityName}}</option>
</select>

파트 II - 페이로드 크기 변경

코드를 바로 잡은 후 노드 익스프레스 서버에 접속하여 루트의 루프를 1000개의 항목에서 정지하도록 변경했습니다.모든 것이 정상적으로 동작했습니다.

이 시점에서 0을 추가하기 시작하면 어떻게 되는지 궁금했습니다.그래서 10K 항목에서는 로드 옵션에 1~2초가 걸리고, 드롭다운을 열면 스트레스로 인해 지연의 징후가 나타나며, 50K 항목에서는 드롭다운을 여는 데 약 5초가 걸립니다.

결산

문제는 어레이의 크기가 아닙니다.Vuex는 209,579개의 아이템 어레이를 800ms 이내에 취득할 수 있습니다.이 어레이에는 Express.js에 의한 백엔드 파싱이 포함되어 있습니다(스택 전체가 로컬이기 때문에 네트워크 지연은 없습니다).

두 번째 또는 세 번째 문자부터 목록이 시작되는 자동 완성을 시도합니다.

답장해준 멤버들 덕분이에요.

겟터라는 이름을 가지고 있습니다.getCityNames.$store.getters.getCityNames$store.cityNames.

그래서 변화

<option v-for="cityName in $store.cityNames">{{cityName}}</option>

로.

<option v-for="cityName in $store.getters.getCityNames">{{cityName}}</option>

템플릿에 삽입하는 것보다 계산된 속성을 사용하도록 리팩터링하는 것이 좋습니다.

<option v-for="cityName in cityNames">{{cityName}}</option>

//script
computed: {
    cityNames() {
        return this.$store.getters.getCityNames;
    }
}

언급URL : https://stackoverflow.com/questions/50083946/vue2-vuex-not-rendering-array-that-is-set-successfully-in-store

반응형