렌더링 전에 비동기 데이터를 대기할 구성 요소 가져오기
개체를 다시 가져오기 위해 엔드포인트를 호출합니다. 개체를 호출하면 데이터를 가져오지만 구성 요소가 데이터를 가져와 렌더링할 만큼 빠르지 않습니다.대신 컴포넌트는 데이터가 있어야 하는 빈 값을 사용하여 렌더링합니다.
생성 시 코드를 중단하고 몇 초 후에 계속하면 텍스트가 올바르게 렌더링됩니다.
데이터가 복구될 때까지 렌더링하지 않도록 구현하려면 어떻게 해야 합니까?
내 API 호출:
checkScenarioType: function () {
    this.$http.get('ScenariosVue/GetScenarioTypeFromParticipant/' + this.ParticipantId).then(response => {
        // get body data
        this.ScenarioType = response.body.value;
        if (this.ScenarioType.timeConstraint) {
            store.commit('switchConstraint');
        }
    }, response => {
        // error callback
    });
}
 
문제가 있는 컴포넌트:
var questionArea = Vue.component('questionarea', {
    props: ["scenariotype"],
    data: function () {
        return ({
            position: "",
            vehicleType: ""
        });
    },
    methods: {
        transformValuesForDisplay: function () {
            switch (this.scenariotype.perspective) {
                case 1: {
                    this.position = "Driver";
                    this.vehicleType = "Autonomous";
                    break;
                }
                case 2: {
                    this.position = "Passenger";
                    this.vehicleType = "Manually Driven";
                    break;
                }
                case 3: {
                    this.position = "Driver";
                    this.vehicleType = "Manually Driven";
                    break;
                }
            }
        }
    },
    beforeMount() {
        this.transformValuesForDisplay();
    },
    template: 
    `<h1>You are the {{ this.position }}! What should the {{ this.vehicleType }} car do?</h1>`
});
데이터의 비동기 로딩이 있는 경우 일반적으로 간단한v-if데이터가 존재할 때까지 요소를 숨깁니다.
템플릿은 다음과 같습니다.
<h1 v-if="position">You are the {{ position }}! What should the {{ vehicleType }} car do?</h1>
 
의 사용에 주의해 주세요.this템플릿은 불필요합니다.
또한, 당신의 경우엔,beforeMount()훅을 사용하면 (깊이/깊이) 워치를 소품에 추가하여 외부에서 로드될 때 변경 사항을 확인할 수 있습니다.
  watch: {
    scenariotype: {
      handler: function(newValue) {
            this.transformValuesForDisplay();
      },
      deep: true,
      immediate: true
    }
  },
 
아래는 완전한 데모입니다.
Vue.component('questionarea', {
  props: ["scenariotype"],
  data: function () {
    return ({
      position: "",
      vehicleType: ""
    });
  },
  methods: {
    transformValuesForDisplay: function () {
      switch (this.scenariotype.perspective) {
        case 1: {
          this.position = "Driver";
          this.vehicleType = "Autonomous";
          break;
        }
        case 2: {
          this.position = "Passenger";
          this.vehicleType = "Manually Driven";
          break;
        }
        case 3: {
          this.position = "Driver";
          this.vehicleType = "Manually Driven";
          break;
        }
      }
    }
  },
  watch: {
  	scenariotype: {
      handler: function(newValue) {
    		this.transformValuesForDisplay();
      },
      deep: true,
      immediate: true
    }
  },
  template: 
  `<h1 v-if="position">You are the {{ position }}! What should the {{ vehicleType }} car do?</h1>`
});
new Vue({
  el: '#app',
  data: {
  	ScenarioType: {perspective: null}
  },
  methods: {
    checkScenarioType: function () {
      this.$http.get('https://reqres.in/api/users/2').then(response => {
        // get body data
        this.ScenarioType.perspective = response.body.data.id; // for testing purposes only
      }, response => {
        // error callback
      });
    }
  },
  mounted: function() {
    this.checkScenarioType();
  }
}) 
  <script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-resource"></script>
<div id="app">
  <p>Notice while it is null, the h1 is hidden: {{ ScenarioType }}</p>
  <br>
  <questionarea :scenariotype="ScenarioType"></questionarea>
</div> 
 언급URL : https://stackoverflow.com/questions/49477230/get-component-to-wait-for-asynchronous-data-before-rendering
'programing' 카테고리의 다른 글
| Vuex 이름 지정 저장소 집합 두 상태 (0) | 2022.08.27 | 
|---|---|
| EXE 또는 MSI 설치가 아닌 zip 파일로 최신 JRE/JDK를 입수하려면 어떻게 해야 합니까? (0) | 2022.08.27 | 
| JUnit 4 테스트에서 특정 예외가 발생한다고 주장하는 방법은 무엇입니까? (0) | 2022.08.27 | 
| vue-cli 웹 팩 인코딩 이미지 base64 사용 안 함 (0) | 2022.08.27 | 
| Java를 사용하여 정규 표현을 사용하여 더 큰 문자열의 하위 문자열 검색 (0) | 2022.08.27 |