首页 > 解决方案 > Vue 大喊对象未定义,同时它在需要加载它的范围内

问题描述

我想做类似的事情:

但由于某种原因,我收到错误

[Vue 警告]:渲染错误:“TypeError: this.json[index] is undefined”

如果 bool dataIsLoaded 应该确保它被加载,那怎么可能呢?


<div id="app" v-if="dataIsLoaded">
    <div v-for="(obj, index) in json.data">
        {{ parse(index) }}
    </div>
</div>

el: '#app',
data: {
    json: null,
    dataIsLoaded: false
},
beforeCreate: function () {
    fetch("api")
      .then(r => r.json())
      .then(json => {
          this.json = json;
          this.dataIsLoaded = true;
      });
},
methods:
{
    parse: function(index)
    {
        var type = this.json[index].name;
        var body = this.json[index].age;

        (...)

        return ...
    }
}

同时这样的事情正常工作

<div id="app" v-if="dataIsLoaded">
    <div v-for="(obj, index) in json.data">
        {{ index }}{{ obj }}
    </div>
</div>

此外:

parse: function(index)
{
    console.log(index);
    var type = this.json[index].name;
    var body = this.json[index].age;

    (...)

    return ...
}

console.log(index) 返回例如 0,因此 index 具有适当的值。

标签: javascriptvue.jsvuejs2frontend

解决方案


推荐阅读