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

Vue.js中如何获取Axios GET请求返回数据并实现条件渲染展示?

解决Vue.js中Axios GET请求数据的获取与展示问题

嘿,我来帮你搞定这个问题!不管你用的是Vue 2的选项式API还是Vue 3的组合式API,下面的方案都能让你轻松获取Axios返回的数据,还能通过条件渲染灵活展示不同状态(加载中、有数据、请求失败等)。

基础场景:直接获取GET请求数据并展示

先从最常用的场景入手,我们分两种API风格来举例:

1. Vue 2/3 选项式API写法

<template>
  <div class="data-container">
    <h2>我的数据列表</h2>
    <!-- 有数据时渲染列表 -->
    <ul v-if="dataList.length">
      <li v-for="item in dataList" :key="item.id">
        {{ item.title }} - {{ item.description }}
      </li>
    </ul>
    <!-- 加载中状态 -->
    <p class="loading" v-else-if="isLoading">正在加载数据...</p>
    <!-- 请求失败或无数据状态 -->
    <p class="error" v-else>
      {{ error ? '加载失败,请重试' : '暂无数据' }}
    </p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      dataList: [], // 存储返回的数据
      isLoading: false, // 加载状态标记
      error: null // 错误信息
    };
  },
  // 组件挂载后立即请求数据
  mounted() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      this.isLoading = true;
      try {
        // 替换成你的API接口地址
        const response = await axios.get('/api/your-data-endpoint');
        // 重点:Axios返回的response.data才是服务器的实际响应数据
        this.dataList = response.data;
      } catch (err) {
        this.error = err;
        console.error('请求出错:', err);
      } finally {
        // 不管成功失败,都结束加载状态
        this.isLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.loading { color: #666; }
.error { color: #e74c3c; }
</style>

2. Vue 3 组合式API写法(<script setup>)

组合式API的逻辑更集中,适合复杂组件:

<template>
  <div class="data-container">
    <h2>我的数据列表</h2>
    <ul v-if="dataList.length">
      <li v-for="item in dataList" :key="item.id">
        {{ item.title }} - {{ item.description }}
      </li>
    </ul>
    <p class="loading" v-else-if="isLoading">正在加载数据...</p>
    <p class="error" v-else>
      {{ error ? '加载失败,请重试' : '暂无数据' }}
    </p>
  </div>
</template>

<script setup>
import axios from 'axios';
import { ref, onMounted } from 'vue';

// 声明响应式变量
const dataList = ref([]);
const isLoading = ref(false);
const error = ref(null);

// 封装获取数据的函数
async function fetchData() {
  isLoading.value = true;
  try {
    const response = await axios.get('/api/your-data-endpoint');
    dataList.value = response.data;
  } catch (err) {
    error.value = err;
    console.error('请求出错:', err);
  } finally {
    isLoading.value = false;
  }
}

// 组件挂载时触发请求
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.loading { color: #666; }
.error { color: #e74c3c; }
</style>

针对你的API封装了Ajax函数的场景

如果你的API已经封装了自己的Ajax函数(比如统一处理请求头、错误拦截),直接调用这个封装好的函数就行,不用重复写Axios逻辑:

假设你的API封装文件是api.js:

// api.js
import axios from 'axios';

// 封装的GET请求函数
export async function getMyData() {
  // 这里可以加统一的请求配置,比如token、baseURL等
  const response = await axios.get('/api/your-data-endpoint');
  // 可以在这里提前处理数据,比如只返回需要的字段
  return response.data;
}

然后在Vue组件中调用:

<script setup>
import { ref, onMounted } from 'vue';
import { getMyData } from './api.js';

const dataList = ref([]);
const isLoading = ref(false);
const error = ref(null);

async function loadData() {
  isLoading.value = true;
  try {
    // 直接调用封装好的API函数
    dataList.value = await getMyData();
  } catch (err) {
    error.value = err;
    console.error('请求出错:', err);
  } finally {
    isLoading.value = false;
  }
}

onMounted(() => {
  loadData();
});
</script>

额外的实用技巧

  • 处理嵌套数据:如果你的API返回的是嵌套结构(比如{ code: 200, data: [...], msg: 'success' }),记得取response.data.data来赋值,根据实际返回结构调整。
  • 复杂条件渲染:可以用计算属性简化模板逻辑,比如:
    import { computed } from 'vue';
    const hasValidData = computed(() => dataList.value.length > 0 && !error.value);
    
    然后模板里用v-if="hasValidData"。
  • 手动触发请求:如果需要用户点击按钮才请求数据,把fetchData绑定到按钮的@click事件即可。

内容的提问来源于stack exchange,提问作者Valerio Gambino

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:15:28