【问题标题】:Javascript: Error when loading the pageJavascript:加载页面时出错
【发布时间】:2019-01-23 12:31:31
【问题描述】:

我正在进行 API 调用,每次页面加载时都会出现此错误,我不知道为什么。 谁能告诉我为什么? 我试着说一下:

这是我使用总金额的标记:

<div class="summary__graph">
        <div class="graph__header">
          <h3 class="headline">Fordeling</h3>
          <p class="answers">{{company.amount.total}} besvarelser</p>
        </div>

这是我定义我的公司的地方,我填写了总价值

 data () {
    return {
      selected: 1,
      datacollection: null,
      datacollection2: null,
      datacollection3: null,
      company: '',
      isActive: false,
      scoreLine: null,
      timeBar: null,
      answerPercent: null

    }
  },

vue.js 挂载和方法

  mounted () {
    this.getStoreScore()
    this.fillData()
    this.fillData2()
    this.fillData3()
    this.fillDataScoreLine()
    this.fillDataTimeBar()
    this.fillDataAnswerPercent()
  },


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

谁能告诉我为什么它给了我这个错误? :D

【问题讨论】:

  • company.amount.total 未在 axios.post(..) 响应之前定义。在之前将其初始化为 null 或使用 if 包装您的 html
  • 我建议编辑您的问题以包含错误文本,而不是粘贴图像。这让试图帮助您的人更容易阅读,也让其他人更容易在 Google 上找到相同的问题。

标签: javascript json vue.js


【解决方案1】:

因为您正在进行 API 调用,所以页面会在您收到任何数据之前呈现。您收到错误是因为在呈现页面时 company.amount 未定义。有一些可能的修复方法:要么延迟页面渲染,直到收到所有数据,要么编写一个快速的 if 条件

<p class="answers">{{company.amount.total}} besvarelser</p>

更多信息:https://vuejs.org/v2/guide/conditional.html

编辑:你的代码会变成

<p v-if="company.amount" class="answers">{{company.amount.total}} besvarelser</p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 2014-10-04
    相关资源
    最近更新 更多