在获取数据之前的Vue渲染组件

时间:2018-09-03 11:25:21

标签: javascript api vue.js vue-component

当我使用数据属性渲染组件时,它会在获取数据之前加载html。这导致没有数据显示。直到我在组件内部进行api调用,并带有一个呈现该功能的标签。

谁能告诉我在获取数据后如何渲染组件。我已经尝试了v-if条件。它使我的页面没有数据。如果我删除v-如果它说无法读取未定义的属性。

  <div class="score">
          <p class="number">{{company.storeScore}} test</p>
          <p class="text">Tilfredhedscore</p>
  </div>

getStoreScore (condition) {
      return axios.post('API-LINK', {
        storeId: '5b7515ed5d53fa0020557447',
        condition: condition
      }).then(response => {
        this.company.storeScore = response.data.result
        this.company.amount = {
          'total': response.data.amount.total,
          'zero': {
            'amount': response.data.amount.zero,
            'percentage': (response.data.amount.zero !== 0 ? response.data.amount.zero / response.data.amount.total * 100 : 0)
          },
          'one': {
            'amount': response.data.amount.one,
            'percentage': (response.data.amount.one !== 0 ? response.data.amount.one / response.data.amount.total * 100 : 0)
          },
          'two': {
            'amount': response.data.amount.two,
            'percentage': (response.data.amount.two !== 0 ? response.data.amount.two / response.data.amount.total * 100 : 0)
          },
          'three': {
            'amount': response.data.amount.three,
            'percentage': (response.data.amount.three !== 0 ? response.data.amount.three / response.data.amount.total * 100 : 0)
          }

        }
      })
    }


data () {
    return {
      selected: 1,
      company: {},
      isActive: false,
      test12345: {}
    }
  },

error message

预先感谢

更新(已解决): 公司定义在此之前为空

data() {
  return{
    company: null
  }
}

这导致呈现我的数据时出现问题。 解决方法是在我要使用的数组中定义内容

例如

data() {
  return{
    company: {
      amount: {
       total: null
      }
    }
  }
}

1 个答案:

答案 0 :(得分:2)

很高兴您自己找到解决方案。好吧,我正在提出另一种解决方案。 您可以使用布尔值来完成此操作。 方法如下:

data() {
  return{
    company: null,
    is_data_fetched: false
  }
}

并在获取数据后更新此布尔值。

getStoreScore (condition) {
    return axios.post('API-LINK', {
        storeId: '5b7515ed5d53fa0020557447',
        condition: condition
    }).then(response => {
        this.company.storeScore = response.data.result;
        this.is_data_fetched = true;
    });
}

然后使用此布尔值在获取数据之前停止呈现。

  <div class="score" v-if="is_data_fetched">
          <p class="number">{{company.storeScore}} test</p>
          <p class="text">Tilfredhedscore</p>
  </div>