如何通过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
相关产品推荐
相关产品推荐

