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

如何在Vue.js中导入TypeScript API文件的attending和emailsend数据?

解决Vue中调用封装的Axios API获取到函数而非数据的问题

问题根源

你直接赋值attending = users.attending拿到的是API请求函数的引用——因为users.attending本身是一个返回Promise的异步函数,必须调用它才能触发请求、获取后端返回的数据。

正确操作步骤

1. 确认API封装结构(参考示例)

假设你的封装文件api/users.ts是类似这样的结构:

import axios from 'axios';

export const users = {
  // 异步请求函数,返回Promise
  attending: () => axios.get('/api/users/attending'),
  emailsend: (payload: { email: string }) => axios.post('/api/users/emailsend', payload)
};

2. 在Vue组件中正确调用获取数据

选项式API写法

<template>
  <div>
    <div v-if="loading">加载中...</div>
    <ul v-else>
      <li v-for="user in attendingUsers" :key="user.id">{{ user.name }}</li>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { users } from '@/api/users'; // 替换成你的实际文件路径

// 建议定义数据类型,提升类型安全
interface User {
  id: number;
  name: string;
}

export default defineComponent({
  data() {
    return {
      attendingUsers: [] as User[],
      loading: false
    };
  },
  async mounted() {
    this.loading = true;
    try {
      // 调用API函数,用await等待异步请求完成
      const res = await users.attending();
      this.attendingUsers = res.data;
    } catch (err) {
      console.error('获取数据失败:', err);
    } finally {
      this.loading = false;
    }
  }
});
</script>

组合式API(

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:47:45