【问题标题】:vue.js - method can't iterate over array propertyvue.js - 方法不能迭代数组属性
【发布时间】:2018-11-12 20:17:41
【问题描述】:

我的应用通过 axios 从 api 读取 json 数据数组。 我将数组存储在应用程序属性中。一切都很好,我可以检查并查看数组数据。

当一个方法应该遍历数组时,它会给出一个错误消息:

[Vue warn]: Error in render: "TypeError: Cannot read property 'length' of null"

这是我的应用程序中的代码:

"use strict";

const app = new Vue({
    el: '#app',
    data: {
        diskstatus: null,
    },
    methods: {
        hasServer: function (serverName) {
            for (let i = 0; i < this.diskstatus.length; i++) {
                if (this.diskstatus[i].ServerName == serverName) {
                    return 'Y';
                }
            }
            return 'N';
        }
    },
    mounted() {
        axios
            .get('api/diskstatus')
            .then(response => {
                this.diskstatus = response.data.rows;
            })
            .catch(err => {
                console.log(err)
            });
    }
});

知道为什么方法中的代码没有将属性视为数组吗?

我可以 console.log 数组,它看起来很完美。 提前感谢您的反馈!

【问题讨论】:

  • diskstatus 最初设置为 null。也许hasServer 调用是在加载统计数据之前发生的?
  • 显示您尝试v-for的HTML。
  • 显示善意回报。

标签: vuejs2


【解决方案1】:

显然,v-for 无法对 null 进行操作,因为 null 不是可迭代

如果您尝试在最初为 null 的属性上使用 v-for,但后来异步变为 Array,您有两种选择:

  1. 初始化diskstatus: [] 而不是null
  2. 在您尝试v-for 的元素上,添加保护:v-if="diskstatus"

【讨论】:

  • 我的错误是将属性初始化为 null 而不是 []。它现在完美无缺!另外,我喜欢保护输出的想法!
猜你喜欢
  • 2015-12-12
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
相关资源
最近更新 更多