vuejs2 - 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 数组,它看起来很完美。提前感谢您的反馈!
解决方案
显然,v-for
不能操作,null
因为null
is not iterable。
如果您尝试使用v-for
最初是null
且仅稍后异步变为 的属性,则Array
有两种选择:
- 初始化
diskstatus: []
而不是null
- 在您尝试的元素上
v-for
,添加警卫:v-if="diskstatus"
。
推荐阅读
- python - 如何在 Mac OS Catalina zsh shell 上永久设置用户 PATH
- alfresco - Alfresco 从 PPTX 文件创建 PDF 再现
- r - 将多边形 shapefile 导出为 XY 顶点对列表
- neo4j - Neo4J 查询最常见的关系
- python - iPython:用 try/except 杀死一个 for 循环?
- python - 分配简单变量命名后的 KeyError
- python - 为什么当我尝试将元组输入到树视图时只有一半被读取
- php - 计算两列值不匹配的行数
- bootstrap-4 - 格式化 thymeleaf 表头,垂直对齐
- java - 关于如何在 Java 中构建我自己的 StringBuilder 类的建议?