javascript - 如果数据函数中的数组为空,Vue 模板将不会呈现
问题描述
我在使用 Vue 模板时遇到问题,除非data
已经填充了声明的数组,否则页面上的任何元素都不会呈现。
问题是data
只有在提交表单进行 API 调用后才会填充。
浏览器控制台读取Error in render: "TypeError: Cannot read property 'response' of undefined"
如果我注释掉{{classes.data.response}}
表单显示但不会。
这是代码的样子。
<template>
<div class="container">
<form @submit="getClass">
<input type="text" placeholder="Search..." v-model="class_id">
<button type="submit">Search</button>
</form>
<br>
<div v-if="classes"> <!-- conditionally render if array has results -->
{{classes.data.response}} <!-- form shows when this is commented out -->
</div>
</div>
</template>
数据块
data() {
return {
classes: []
};
},
...
并且方法块
methods: {
...
// Request
axios(config)
.then(response => (this.classes = response))
.catch(function (error) {
console.log('There was an error :' , error);
});
}
}
我对 Vue 比较陌生,所以如果有人能告诉我这里出了什么问题,我将不胜感激。提前致谢!
解决方案
this.classes.data.response 未定义
在将响应分配给 时,您可以尝试更具体classes
。而不是this.classes = response
,这样做this.classes = response.data.response
。response.data.response
是您要查找的数组,而不是response
.
methods: {
...
// Request
axios(config)
.then(response => (this.classes = response.data.response))
.catch(function (error) {
console.log('There was an error :' , error);
});
}
}
然后在模板中只写{{ classes }}
代替{{ classes.data.response }}
,也v-if="classes.length > 0"
代替只是v-if="classes"
。
v-if="classes"
将一直是true
v-if="classes.length > 0"
将是true
当数组中有更多的 0 元素时
为什么
由于 API 请求的异步特性,表单尝试呈现的那一刻this.classes
仍然是您定义的空数组。只有稍后,一旦 API 请求完成,this.classes
就会有它需要的数据。
推荐阅读
- ruby-on-rails - 使用 ActiveRecord 或 AREL 构建 MySQL 插入忽略语句
- php - 爆炸动画 GIF 和操作帧(GD 库)
- ios - 有没有办法在不创建框架的情况下创建一个分布在众多 Swift 文件中的类库?
- c++ - 从自定义结构数组中提取数据
- python - 如何将元素添加到空的 2d numpy 数组
- google-sheets - 如果标题在 Google 表格中匹配,则从列中导入所有值
- ruby - 如何通过 ERB.result_with_hash 绑定
- c# - 如何创建使用工厂模式实例化对象的正确脚本
- java - 使用 postgresql 进行 elasticsearch 全文搜索
- java - 正则表达式:将字符串拆分为固定长度,不带分词并包括特殊字符