【vant】打开vant表单的正确形式(基于vant表单的二次封装)

news/2024/10/17 10:24:07/

前言

最近在用vant做关于移动端的项目,由于表单字段太多,不想写直接写到template中,这样太繁琐了,所以我们以把表单弄成schema配置形式:

// data.ts
import type { ItemSchema } from '@/typing/helper';
import { StudentField } from '@/components';
import { getDictTextByCode } from '@/data/dict';import {textField,switchField,dividerField,dictField,selectField,entityField,
} from '@/helpers';export const baseFormSchema: ItemSchema[] = [dividerField('普通文本'),textField('name', '姓名', { required: true }),dividerField('文本域'),textField('address', '地址', { type: 'textarea' }),dividerField('是否字段'),switchField('isMarried', '是否婚配'),dividerField('字典选择'),dictField('marital', '婚姻情况', 'marital'),dividerField('select'),selectField('way', '交通工具', [{ text: '汽车', code: 1 },{ text: '步行', code: 2 },]),dividerField('实体选择(学生)'),entityField('studentId', '学生', StudentField, {change(record) {console.log(record);},}),
];

form组件使用:

<template><div class="content"><code><pre>{{ formValue }}</pre></code><TwiceForm :form-schema="baseFormSchema" v-model="formValue"></TwiceForm></div>
</template><script setup lang="ts">import { ref } from 'vue';import { TwiceForm } from '@/components';import { baseFormSchema } from '@/views/form/data';const formValue = ref({name: '',age: '',address: '',isMarried: true,marital: -1,way: 1,studentId: '',});
</script>
<style lang="less" scoped></style>

就是通过数据驱动生成表单(效果如下)。
在这里插入图片描述
也可以戳链接亲自体验:vant_twice_form

小成果

这样不仅表单字段配置起来方便,更能解决一些业务交互上的一些需求:

比如根据一个字段值判断是否需要填写后续字段

请添加图片描述

又比如选实体字段时把带回来的记录显示到表单中:

请添加图片描述
下面就看看我是怎么做的吧。

实现步骤(以文本字段为例):

  • 根据字段类型封装生成该类型schema的方法
import { merge } from 'lodash-es';
import type { Props, ItemSchema } from '@/typing/helper';
import { Field } from 'vant';/** * 文本字段* @param field* @param label* @param props*/
export function textField(field: string,label: string,props?: Props
): ItemSchema {return {component: Field,props: merge({field,label,placeholder: `请输入${label}`,rules: props?.required? [{ required: true, message: `${label}不能为空` }]: [],},props),};
}
  • 把生成的schema列表遍历出来
<template><Form ref="formRef"><template v-for="schema in formSchema" :key="schema"><template v-if="schema?.props?.field"><template v-if="calcShow(schema)"><component:is="schema.component"v-bind="schema.props"v-model="formValue[schema.props.field]"@change="(record) =>schema?.props?.change &&schema?.props?.change(record, formValue, formSchema)"/></template></template><component v-else :is="schema.component" v-bind="schema.props" /></template></Form>
</template><script setup lang="ts">import { ref, unref, watch, computed } from 'vue';import { Form } from 'vant';import type { ItemSchema } from '@/typing/helper';const props = defineProps<{formSchema: ItemSchema[];modelValue: any;}>();const formValue = ref(props.modelValue);const formRef = ref();const emits = defineEmits<{(e: 'update:modelValue', params: any): void;(e: 'submit', params: any): void;}>();watch(formValue.value, (value) => {emits('update:modelValue', unref(value));});const calcShow = computed(() => (schema: ItemSchema) => schema?.props?.show === false ? false : true);defineExpose({// 表单校验validate: async () => await formRef.value.validate(),// 设置值(清空、回显)setValue: function <T>(value: T) {formValue.value = value;},});
</script>
<style lang="less" scoped></style>
  • 配置schema
import {textField,dividerField,
} from '@/helpers';export const baseFormSchema: ItemSchema[] = [dividerField('普通文本'),textField('name', '姓名', { required: true }),
]
  • 使用form组件
<template><div class="content"><code><pre>{{ formValue }}</pre></code><TwiceForm :form-schema="baseFormSchema" v-model="formValue"></TwiceForm></div>
</template><script setup lang="ts">import { ref } from 'vue';import { TwiceForm } from '@/components';import { baseFormSchema } from '@/views/form/data';const formValue = ref({name: '',age: '',address: '',isMarried: true,marital: -1,way: 1,studentId: '',});
</script>
<style lang="less" scoped></style>

就先记录到这里,后续更新追记。感兴趣可以仓库看源码;


http://www.ppmy.cn/news/798662.html

相关文章

写给前端的 Docker 入门终极指南,别再说不会用 Docker 了!

点击上方 前端Q&#xff0c;关注公众号 回复加群&#xff0c;加入前端Q技术交流群 富 Web 时代&#xff0c;应用变得越来越强大&#xff0c;与此同时也越来越复杂。集群部署、隔离环境、灰度发布以及动态扩容缺一不可&#xff0c;而容器化则成为中间的必要桥梁。 本节我们就来探…

【软考-中级】系统集成项目管理工程师-【1信息化知识】

持续更新。。。。。。。。。。。。。。。 信息化知识 一 、考试重点 &#xff08;掌握&#xff09;1.1 信息传输模型1.2 信息质量属性1.3 信息系统生命周期&#xff08;常考&#xff09;1.4 信息化体系六要素&#xff08;常考&#xff09;1.5 信息技术发展及趋势1.6 电子政务1.…

Aurora依托AWS加速Aurora Driver的开发

在AWS的高性能基础设施和广泛的功能组合支持下&#xff0c;Aurora使用机器学习和日均数百万次基于云的模拟&#xff0c;以安全方式快速训练、测试和验证其自动驾驶汽车技术 西雅图--(美国商业资讯)--亚马逊(Amazon.com, Inc., NASDAQ: AMZN)旗下公司亚马逊网络服务(Amazon Web…

国科大UCAS大气物理期末复习笔记/大气物理基础入门

2021秋季学期&#xff0c;主讲教师为卞建春研究员&#xff0c;其中郄秀书研究员介绍了大气电学相关。 考虑到大气物理学基础的在日后研究中十分重要&#xff0c;故稍作整理。 主要参考为课程PPT、作业、大纲 书籍&#xff1a; Atmospheric Science John M. Wallace & Peter…

亚马逊CTO Werner Vogels:2023年及未来五大技术趋势预测

点击上方【凌云驭势 重塑未来】 一起共赴年度科技盛宴&#xff01; 近年来&#xff0c;几次全球性危机占据了我们的日常生活&#xff0c;因此看看我们是否可以利用技术来解决这些棘手的人类问题。如今&#xff0c;我们可以从很多互联设备获取数据&#xff0c;例如&#xff1a;可…

亚马逊首席技术官:2023年及未来五大技术趋势预测 | 美通社头条

美通社消息&#xff1a;近年来&#xff0c;随着我们经历的数次全球危机&#xff0c;如何借助技术解决人类棘手问题至关重要。如今&#xff0c;我们获取数据的来源比以往任何时候都多&#xff0c;包括可穿戴设备、医疗设备、环境传感器、视频捕获和其他联网设备。当这些数据与计…

尾涡流matlab仿真,电涡流检测仿真软件的设计(附MATLAB程序)(测控技术)☆

摘 要 电涡流检测技术在近年来发展十分迅猛,以其很高的可靠性和精确度受到广泛的欢迎,在各行各业的检测系统中被大量地应用。MATLAB是一款具备强大数学运算能力的软件,被广泛的应用于科学计算、控制系统以及信息处理等领域的分析、仿真和设计工作。 电涡流无损检测领域是当…