You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue新手求助:属性未定义警告及API数据无法显示问题

解决Vue中API数据不显示及属性未定义警告的问题

嘿,我一眼就揪出问题所在啦!你的代码里有两个关键小疏漏,直接导致了控制台警告和数据不显示的情况:

1. 致命拼写错误:data写成了date

Vue组件的响应式属性必须放在data选项中,但你不小心把它拼写成了date()方法——Vue完全不会识别这个自定义方法,自然不会把searchValue和results挂载到组件实例上,模板里引用它们时就会触发“属性未定义”的警告。

把拼写修正过来就好:

// 错误写法
date() {
  return {
    searchValue: '',
    results: [],
  };
}

// 正确写法
data() {
  return {
    searchValue: '',
    results: [],
  };
}

2. 请求成功后未给results赋值

你在axios请求成功后只打印了返回的数据,但没有把数据同步到组件的results属性里,就算API返回了正确数据,模板里的列表也没法拿到数据来渲染。

在then回调里加上赋值逻辑:

axios.get(`${API}?q=${this.searchValue}&media_type=image`)
  .then((response) => {
    console.log(response.data.collection.items);
    // 将返回数据赋值给results,让模板能获取到
    this.results = response.data.collection.items;
  })
  .catch((error) => {
    console.log(error);
  });

修正后的完整代码

<template>
  <div class="wrapper">
    <div class="search">
      <label for="search">Search</label>
      <input id="search" name="search" @input="handleInput" v-model="searchValue" />
      <ul>
        <li v-for="item in results" :key="item.data[0].nasa_id">
          <p>{{ item.data[0].description }}</p>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import axios from 'axios';
import debounce from 'lodash.debounce';
const API = 'https://images-api.nasa.gov/search';
export default {
  name: 'Search',
  data() { // 修正为正确的data选项
    return {
      searchValue: '',
      results: [],
    };
  },
  methods: {
    handleInput: debounce(function () {
      axios.get(`${API}?q=${this.searchValue}&media_type=image`)
        .then((response) => {
          console.log(response.data.collection.items);
          this.results = response.data.collection.items; // 添加数据赋值
        })
        .catch((error) => {
          console.log(error);
        });
    }, 500),
  },
};
</script>

做完这两处修改后,控制台的警告会立刻消失,输入搜索内容后,API返回的数据也能正常显示在列表里啦!

内容的提问来源于stack exchange,提问作者Damian Kacprzak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:12:30