[Vue+FormKit]:将异步数据加载到架构生成的表单中



TL;DR是否有将异步数据加载到<FormKitSchema>的方法?

我正在尝试获取异步数据,并将其加载到从JSON模式(<FormKitSchema>)生成的FormKit表单中。我似乎找不到一个例子,我已经尝试了几种方法,但都没有成功。

我知道input元素的value属性只有在最初渲染时才会使用,这很酷。然而,我似乎无法先获取数据,然后有条件地加载<FormKitSchema>(使用v-if没有任何帮助)。渲染似乎必须在加载初始组件的情况下执行,否则什么都不显示。

示例:formComponent.vue(<FormComponent>)

<template>
<FormKitSchema :schema="schema" :data="asyncData"/>
</template>
<script setup>
import {reactive, ref} from 'vue';
const getData = async () => {
return new Promise((resolve) => {    
setTimeout(() => {
resolve({name: "How do I get this into the form???"})
}, 1500)
})
};
const asyncData = reactive({
userData: await getData(), // Using 'await' here seems to prevent the form from ever loading
submit: async (formData, node) => {
console.log("submit: ", {formData, node});
}
})
const schema = [
{
$cmp: 'FormKit',
props: {
type: 'form',
id: 'form',
onSubmit: '$submit',
plugins: '$plugins',
actions: false,
},
children: [
{
$formkit: 'text',
name: 'fullname',
label: '*Full Name',
placeholder: 'Full Name',
value: "$userData.name",
validation: 'required'
},
{
$formkit: 'submit',
label: 'Save',
disabled: '$get(form).state.valid !== true'
}
]
}
]
</script>

这不是FormKitFormKitSchema的问题。这是在Vue的reactive()函数中使用await的问题。

为了在组件的初始reactive()参数对象中使用promise解析值(即userData: await getData())(类似于formComponent.vue示例),调用/父组件必须将它们封装在<Suspense>标记中。否则,Vue似乎根本没有渲染组件,这就是为什么没有错误,也没有显示任何内容。

从关于Suspense的Vue.js文档。。。A component with async setup() must be nested in a <Suspense> in order to be rendered.

因此,问题中的formComponent.vue代码是可以的。只需要在使用<FormComponent>的任何地方向模板添加<Suspense>标签。例如

示例:parentView.vue

<Suspense>
<FormComponent/>
</Suspense>

注:在撰写本文时,<Suspense>元素是实验性的,可能会发生变化。

最新更新