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

Vue.js获取API数据后无法渲染展示问题求助

问题分析与解决

核心问题:响应式数据未正确声明

Vue 2中组件的响应式数据必须在data选项里提前声明,否则直接赋值的变量无法触发视图更新。你当前的ActivitiePage组件没有定义items和loading的响应式数据,导致API返回的数据虽然成功赋值,但视图无法感知到变化,自然无法渲染。

修复步骤

1. 补全ActivitiePage的响应式数据定义

修改ActivitiePage的<script>部分,添加data选项声明所需变量:

<script>
import Item from '@/components/Item.vue';
import SearchBar from '@/components/SearchBar.vue';

export default {
  components: {
    Item,
    SearchBar // 导入后需注册组件
  },
  data() {
    return {
      items: [], // 提前声明响应式数组
      loading: true, // 初始化加载状态
      itemTimes: [] // 用到的变量需提前声明
    }
  },
  created() {
    fetch('/api/v1/Activities/all')
      .then(response => {
        if (!response.ok) {
          throw new Error(`Network response was not ok, status: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
        this.items = data;
        this.loading = false;
      })
      .catch(error => {
        console.error('Error retrieving items:', error);
        this.loading = false;
      });
  },
  methods: {
    onShareButtonClick() { // 绑定的方法需定义
      // 补充分享逻辑
    }
  }
};
</script>

2. 修复Item组件的语法错误

Item.vue的<script>部分存在语法冗余,修正为:

<script>
export default {
  props: {
    item: {
      type: Object,
      required: true // 建议添加必填校验,避免传值异常
    }
  }
}
</script>

3. 修正模板标签缺失问题

ActivitiePage模板里<select>标签缺少开头标签,补上后:

<div id="app">
  <ul>
    <select>
      <option v-for="time in itemTimes" :key="time">{{ time }}</option>
    </select>
    <item v-for="item in items" :key="item.Text" :item="item" @share="onShareButtonClick" />
  </ul>
  <!-- 剩余模板内容不变 -->
</div>

额外检查项

  • 确认API返回的data结构和你测试用的默认items完全一致,重点检查Image、Text字段的大小写是否匹配(Vue对属性大小写敏感)。
  • 打开浏览器控制台,查看是否有未定义变量、属性不存在等报错信息,这类细节问题也会导致渲染失败。

内容的提问来源于stack exchange,提问作者Chris Curt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:42:50