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

如何通过Vueform获取API的响应结果?

Vueform获取API响应结果的实现方法

首先修正你代码里的拼写错误:resposne 应改为 response,笔误会影响响应结果的正常存储。

下面提供两种常用方式获取API返回的响应:

方法一:通过onSubmit钩子处理响应

在Vueform配置中添加onSubmit回调函数,提交成功后可直接拿到响应数据:

<template>
  <Vueform v-bind="vueform"></Vueform>
</template>

<script>
import { useVueform, Vueform } from '@vueform/vueform'
import { ref } from 'vue'

export default {
  mixins: [Vueform],
  setup(props, context) {
    const form = useVueform(props, context)
    
    const handleSubmit = async (response) => {
      // 直接获取API返回的响应数据
      console.log('API响应结果:', response)
      // 可在此添加业务逻辑:比如存储token、页面跳转等
      // localStorage.setItem('token', response.data.token)
    }

    const vueform = ref({
      method: 'POST',
      endpoint: 'http://localhost:5002/api/user/login',
      displayErrors: true,
      response: {
        data: {}
      },
      // 配置提交成功后的回调
      onSubmit: handleSubmit,
      schema: {
        h1: {
          type: 'static',
          tag: 'h1',
          content: 'Input Secret-code',
        },
        code: {
          type: 'text',
          placeholder: 'Code',
          size: 'lg',
        },
        submit: {
          type: 'button',
          buttonLabel: 'Submit',
          submits: true,
          align: 'right',
          size: 'lg',
        }
      },
    })

    return {
      ...form,
      vueform,
    }
  }
}
</script>

方法二:监听form实例的response属性

通过Vue的watch监听form.response,当响应更新时触发业务逻辑:

<template>
  <Vueform v-bind="vueform"></Vueform>
</template>

<script>
import { useVueform, Vueform } from '@vueform/vueform'
import { ref, watch } from 'vue'

export default {
  mixins: [Vueform],
  setup(props, context) {
    const form = useVueform(props, context)
    
    // 监听响应变化,deep设为true以监听对象内部属性
    watch(() => form.response, (newResponse) => {
      if (newResponse.data) {
        console.log('API响应结果:', newResponse.data)
        // 执行你的业务逻辑
      }
    }, { deep: true })

    const vueform = ref({
      method: 'POST',
      endpoint: 'http://localhost:5002/api/user/login',
      displayErrors: true,
      response: {
        data: {}
      },
      schema: {
        h1: {
          type: 'static',
          tag: 'h1',
          content: 'Input Secret-code',
        },
        code: {
          type: 'text',
          placeholder: 'Code',
          size: 'lg',
        },
        submit: {
          type: 'button',
          buttonLabel: 'Submit',
          submits: true,
          align: 'right',
          size: 'lg',
        }
      },
    })

    return {
      ...form,
      vueform,
    }
  }
}
</script>

额外说明:Vueform提交成功后,会自动将API响应赋值给form.response,你也可以在任何需要的地方直接访问form.response.data获取响应内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:16:13