programing

Vue 2.0: 비동기 데이터를 하위 컴포넌트에 전달

goodcopy 2022. 8. 3. 21:44
반응형

Vue 2.0: 비동기 데이터를 하위 컴포넌트에 전달

프로펠을 통해 데이터를 자식에게 전달하는 상위 Vue 구성 요소가 있지만 데이터를 비동기적으로 사용할 수 있으므로 자식 구성 요소가 정의되지 않은 값으로 초기화됩니다.

데이터를 사용할 수 있을 때까지 초기화를 방지하려면 어떻게 해야 합니까?

부모:

  var employees = new Vue({
    el: '#employees',
    data: { ... },
    methods: {
      fetch: function(model, args=null) {

      let url = "/" + model + ".json"
      console.log(url);
      $.ajax({
        url: url,
        success: ((res) => {
          console.log(res)
          this[model] = res;
          this.isLoading = false;
        error: (() =>  {
          this.isLoading = false;
        }),
        complete: (() => {
          // $('.loading').hide();
          this.isLoading = false;
        })
      })

    },
    mounted: function() {
      this.fetch(...)
      this.fetch(...)
      this.fetch('appointments')
    }
  })

내 가져오기 메서드는 여러 번 호출됩니다.

그냥 사용하시면 됩니다.v-if부모 템플릿:

<template v-if="everthingIsReady">
    <child-item :data="data"></child-item>
</template>

다음 시간까지 하위 항목이 생성되지 않습니다.everythingIsReady로 설정되어 있다.true모든 통화가 완료된 후 바로 설정할 수 있습니다.

Promise를 사용합니다.모든 것.

아래 코드에서 당신의 코드를 수정했습니다.fetchmethod를 사용하여 Ajax 콜에서 약속을 반환합니다.그런 다음 이러한 약속을 배열로 수집하여 다음 사용자에게 전달할 수 있습니다.Promise.all모든 에이잭스 콜이 완료되면 조치를 취하도록 하겠습니다.이 경우,isLoading사용할 수 있는 속성v-if사용할 수 있습니다.

var employees = new Vue({
  el: '#employees',
  data: { isLoading: true },
  methods: {
    fetch(model, args=null) {
      let url = "/" + model + ".json"
      const success = res => this[model] = res
      const error = err => console.log(err)
      return $.ajax({url, success, error})
    }
  },
  mounted(){
    let promises = []
    promises.push(this.fetch('stuff'))
    promises.push(this.fetch('otherstuff'))
    promises.push(this.fetch('appointments'))
    Promise.all(promises)
      .then(() => this.isLoading = false)
      .catch(err => console.log(err))
  }
})

언급URL : https://stackoverflow.com/questions/45059832/vue-2-0-passing-asynchronous-data-to-child-component

반응형