首页 > 解决方案 > vue.js - 方法不能迭代数组属性

问题描述

我的应用程序通过 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 数组,它看起来很完美。提前感谢您的反馈!

标签: vuejs2

解决方案


显然,v-for不能操作,null因为nullis not iterable

如果您尝试使用v-for最初是null且仅稍后异步变为 的属性,则Array有两种选择:

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

推荐阅读