Javascript:加载页面时出错

标签 javascript json vue.js

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

What browser says

这是我使用总量的标记:

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

这里是我定义我的公司的地方,我用总值(value)填充

 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

最佳答案

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

快速编写一个 if 条件
<p class="answers">{{company.amount.total}} besvarelser</p>

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

编辑:您的代码将变为

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

关于Javascript:加载页面时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51878879/

相关文章:

javascript - 将输出从 ToDataURL() 传递到 ASP.NET 代码后面的方法?

json - 我必须将 http header 编码为 JSON 吗?

c# - 反序列化 JSON 文件,没有输出出现

javascript - Service Worker已注册成功,但serviceworker.js文件中的代码尚未执行

javascript - 在选择时将一个日期选择器值复制到另一个日期选择器值不起作用

javascript - 带圆圈的背景应保持相同大小

javascript - CSS div 使用坐标定位

javascript - 如何使用 jQuery 在选择框中显示 JSON 数据?

vue.js - 更改 Vue JS 项目的 .vue 文件中的值不起作用

vue.js - 如何正确地将数据从子组件传递到父组件以及将数据从父组件传递到子组件?