首页 > 解决方案 > 如果数据函数中的数组为空,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 比较陌生,所以如果有人能告诉我这里出了什么问题,我将不胜感激。提前致谢!

标签: javascriptvue.jsfrontend

解决方案


this.classes.data.response 未定义

在将响应分配给 时,您可以尝试更具体classes。而不是this.classes = response,这样做this.classes = response.data.responseresponse.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就会有它需要的数据。


推荐阅读