Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现类似 antd(react) 的 useForm 无需手动绑定 v-model,通过 form-item name 属性来作为表单数据的 key 的 hook #7395

Closed
1 task done
guaijie opened this issue Mar 2, 2024 · 1 comment
Labels

Comments

@guaijie
Copy link

guaijie commented Mar 2, 2024

  • I have searched the issues of this repository and believe that this is not a duplicate.

What problem does this feature solve?

通过声明一个 model,并使用表单组件中 v-model 来绑定 model 中的每一个 key 太过麻烦,因为已经使用 form-item 中的 name 来指定了表单数据的 key,这样做相当于重复声明。

希望使用 provider 和 inject 的方式实现通过 const [form] = Form.useForm() 创建的 form 实列传递给 form-item 并收集以 name 作为表单数据 key 的表单数据。

传递 form 实例给到 Form 表单,还可以用来收集 FormItem 的 rules,使得不必y要传递 rules 给 useForm

// before
<script setup>
const model = reactive({})

return {
model
}
</script>
<template>
<a-form >
<a-form-item name="name" label="姓名">
<a-input v-model:value="model.name" /> // 这一步可以在组件中进行,无需手动绑定(我们已知了 ‘name’, 'value' 和 ‘onChange’)
</a-form-item>
<a-form-item name="age" label="年龄">
<a-select v-model:value="model.value" />
</a-form-item>
</a-form>
</template>

// after
<script setup>
const [form] = Form.useForm()

const submit = () => {
const values = form.getFieldsValues()
// ...
}
return {
form,
submit
}
</script>
<template>
// 如果没有传递 form,则内部创建一个 form 实例,并通过 ref 获取它
// 内部创建一个响应式 model 传递给子组件
<a-form :form="form"> 
<a-form-item name="name" label="姓名" :rule="[{required: true, message: ''}]">
<a-input /> // 通过 provider 和 inject 获取最近的 form、model 和 name 并传递给 v-model:value="model[name]"
</a-form-item>
<a-form-item name="age" label="年龄">
<a-select />
</a-form-item>
</a-form>
</template>

What does the proposed API look like?

import { Form } from 'ant-design-vue'

// 创建 form 实例是也会创建一个响应式 model
const [form] = Form.useForm()

const model: Reactive= form.model //收集表单数据

const values = form.getFieldsValues() // 非响应式数据

// 内部拿到 model 后传递给 AInput 组件
// AFormItem 将 model 和 valueProp 传递给 AInput 组件
// const value = defineModel(valueProp ?? 'value')
//

Copy link

github-actions bot commented May 2, 2024

This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 7 days

@github-actions github-actions bot added the Stale label May 2, 2024
@github-actions github-actions bot closed this as completed May 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant