### Install Vue.Draggable.next
Source: https://github.com/vform666/variant-form3-vite/blob/master/lib/vuedraggable/README.md
Commands to install the package using common package managers.
```bash
yarn add vuedraggable@next
npm i -S vuedraggable@next
```
--------------------------------
### Install VForm 3 Dependencies
Source: https://github.com/vform666/variant-form3-vite/blob/master/README.md
Commands to install the VForm 3 package using npm or yarn.
```bash
npm i vform3-builds
```
```bash
yarn add vform3-builds
```
--------------------------------
### Install and Register VForm 3 (Vue 3)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Instructions for installing VForm 3 via npm or yarn and globally registering the components in a Vue 3 project. It also includes the necessary imports for Element Plus and VForm 3 styles.
```bash
# 使用 npm 安装
npm i vform3-builds
# 或使用 yarn 安装
yarn add vform3-builds
```
```javascript
// main.js - 全局注册 VForm 3
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus' // 引入 element-plus 库
import 'element-plus/dist/index.css' // 引入 element-plus 样式
import VForm3 from 'vform3-builds' // 引入 VForm 3 库
import 'vform3-builds/dist/designer.style.css' // 引入 VForm3 样式
const app = createApp(App)
app.use(ElementPlus) // 全局注册 element-plus
app.use(VForm3) // 全局注册 VForm 3(同时注册了 v-form-designer 和 v-form-render 组件)
app.mount('#app')
```
--------------------------------
### Get/Set Single Field Value (JavaScript)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Provides methods to get or set the value of a single form field by its name. Includes examples for retrieving multiple field values and setting them, as well as handling field联动 (e.g., updating city options when province changes).
```javascript
const vFormRef = ref(null)
// 获取单个字段值
const getField = () => {
const nameValue = vFormRef.value.getFieldValue('name')
const cityValue = vFormRef.value.getFieldValue('city')
console.log('姓名:', nameValue, '城市:', cityValue)
}
// 设置单个字段值
const setField = () => {
vFormRef.value.setFieldValue('name', '王五')
vFormRef.value.setFieldValue('city', 'guangzhou')
}
// 字段联动示例
const handleProvinceChange = (provinceCode) => {
// 省份变化时,清空城市选择
vFormRef.value.setFieldValue('city', '')
// 更新城市选项
loadCityOptions(provinceCode)
}
```
--------------------------------
### Hide/Show Widgets (JavaScript)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Enables hiding or showing specific form components. Similar to disable/enable, it accepts a single component name or an array of names. Examples demonstrate conditional visibility based on form state or user input.
```javascript
const vFormRef = ref(null)
// 隐藏组件
const hideFields = () => {
vFormRef.value.hideWidgets(['internalField', 'debugInfo'])
}
// 显示组件
const showFields = () => {
vFormRef.value.showWidgets(['internalField', 'debugInfo'])
}
// 根据选项显示/隐藏字段
const handleTypeChange = (type) => {
if (type === 'personal') {
vFormRef.value.showWidgets('idCard')
vFormRef.value.hideWidgets('businessLicense')
} else if (type === 'company') {
vFormRef.value.hideWidgets('idCard')
vFormRef.value.showWidgets('businessLicense')
}
}
```
--------------------------------
### Get Form JSON from VFormDesigner (Vue)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Demonstrates how to use the `getFormJson` method of the VFormDesigner component to retrieve the current form configuration. The returned JSON includes `widgetList` and `formConfig`, which can be used for saving or further processing.
```javascript
const vfdRef = ref(null)
// 获取当前设计的表单 JSON
const exportFormJson = () => {
const formJson = vfdRef.value.getFormJson()
console.log('组件列表:', formJson.widgetList)
console.log('表单配置:', formJson.formConfig)
// 保存到后端
saveToServer(JSON.stringify(formJson))
// 返回结构示例:
// {
// widgetList: [...], // 表单组件列表
// formConfig: { // 表单全局配置
// modelName: 'formData',
// refName: 'vForm',
// labelWidth: 80,
// labelPosition: 'left',
// layoutType: 'PC',
// cssCode: '',
// functions: '',
// onFormCreated: '',
// onFormMounted: '',
// onFormDataChange: ''
// }
// }
return formJson
}
```
--------------------------------
### Get Form Data with Validation (JavaScript)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Retrieves form data, supporting form validation. Returns a Promise that resolves with form data upon successful validation or rejects with an error message if validation fails. Handles both validated and non-validated data retrieval.
```javascript
const vFormRef = ref(null)
// 获取表单数据(带验证)
const getDataWithValidation = async () => {
try {
const formData = await vFormRef.value.getFormData(true) // needValidation = true
console.log('表单数据:', formData)
return formData
} catch (error) {
console.error('表单验证失败:', error)
throw error
}
}
// 获取表单数据(不验证)
const getDataWithoutValidation = () => {
const formData = vFormRef.value.getFormData(false) // needValidation = false
console.log('表单数据(未验证):', formData)
return formData
}
```
--------------------------------
### Get Global Data Source Variables in VForm 3
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Shows how to retrieve global data source variables (DSV) passed to VForm via props using the `getGlobalDsv` method. This is useful for accessing configuration like API base URLs or authentication tokens. It requires a VForm instance reference.
```javascript
const vFormRef = ref(null)
// Get global data source variables
const getGlobalVars = () => {
const dsv = vFormRef.value.getGlobalDsv()
console.log('API URL:', dsv.apiBaseUrl)
console.log('Token:', dsv.token)
}
```
--------------------------------
### Get Widget Reference (JavaScript)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Retrieves the reference to a specific form component by its name. This allows direct interaction with the component's internal methods, such as setting its state or getting its current value. An option to show errors is also available.
```javascript
const vFormRef = ref(null)
// 获取组件引用
const getComponentRef = () => {
const inputRef = vFormRef.value.getWidgetRef('username', true) // showError = true
if (inputRef) {
// 调用组件方法
inputRef.setDisabled(true)
inputRef.setHidden(false)
const value = inputRef.getValue()
console.log('当前值:', value)
}
}
```
--------------------------------
### Designer Utility Methods
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Methods for clearing the designer, previewing the form, and exporting configurations.
```APIDOC
## POST /designer/utils
### Description
Utility functions to reset the designer state, trigger a preview modal, or export the current form as JSON, code, or SFC.
### Methods
- `clearDesigner()`: Resets the designer to initial state.
- `previewForm()`: Opens the preview dialog.
- `exportJson()` / `exportCode()` / `generateSFC()`: Triggers respective export dialogs.
```
--------------------------------
### Set Form Data (JavaScript)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Batch sets form field values, commonly used for form data backfilling. Supports setting data from a local object or asynchronously from a backend API. Demonstrates how to populate form fields with provided data.
```javascript
const vFormRef = ref(null)
// 设置表单数据
const fillFormData = () => {
const userData = {
name: '李四',
email: 'lisi@example.com',
phone: '13800138000',
city: 'shanghai',
birthday: '1990-01-01'
}
vFormRef.value.setFormData(userData)
}
// 从后端加载数据并回填
const loadAndFillData = async (userId) => {
const response = await fetch(`/api/user/${userId}`)
const userData = await response.json()
vFormRef.value.setFormData(userData)
}
```
--------------------------------
### Basic Draggable Component Usage
Source: https://github.com/vform666/variant-form3-vite/blob/master/lib/vuedraggable/README.md
Demonstrates how to implement the draggable component in a Vue template and register it in the component definition.
```html
{{element.name}}
```
```javascript
import draggable from 'vuedraggable'
export default {
components: {
draggable,
},
data() {
return {
drag: false,
}
}
}
```
--------------------------------
### Global Registration of VForm 3
Source: https://github.com/vform666/variant-form3-vite/blob/master/README.md
How to import and register the VForm 3 library and Element Plus in a Vue 3 application.
```javascript
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import VForm3 from 'vform3-builds'
import 'vform3-builds/dist/designer.style.css'
const app = createApp(App)
app.use(ElementPlus)
app.use(VForm3)
app.mount('#app')
```
--------------------------------
### Render and Manage Forms
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Demonstrates how to use the VFormRender component to display a form, handle data binding, perform validation, and manage form submission.
```vue
提交
```
--------------------------------
### Draggable with Header and Footer Slots
Source: https://github.com/vform666/variant-form3-vite/blob/master/lib/vuedraggable/README.md
Demonstrates the use of header and footer slots to include additional UI elements like buttons within the draggable container.
```html
{{element.name}}
```
--------------------------------
### Configure VFormDesigner Component (Vue)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Demonstrates how to use the VFormDesigner component in a Vue 3 template. It shows how to bind configuration options via props such as designerConfig, bannedWidgets, and globalDsv to customize the designer's behavior and appearance.
```vue
```
--------------------------------
### Vuex Integration
Source: https://github.com/vform666/variant-form3-vite/blob/master/lib/vuedraggable/README.md
Shows how to bind the draggable component to a Vuex store using computed properties with getters and setters.
```javascript
computed: {
myList: {
get() {
return this.$store.state.myList
},
set(value) {
this.$store.commit('updateList', value)
}
}
}
```
--------------------------------
### External Component Interaction in VForm 3
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Explains how to register and interact with external components using VForm 3's `addEC`, `getEC`, and `hasEC` methods. This allows VForm to communicate with components like tables or custom widgets. It requires references to both the VForm instance and the external component.
```javascript
const vFormRef = ref(null)
const myTableRef = ref(null)
// Register an external component
const registerExternalComponent = () => {
vFormRef.value.addEC('mainTable', myTableRef.value)
}
// Call external component methods within form events (e.g., onFormMounted)
const onFormMountedCode = `
if (this.hasEC('mainTable')) {
const tableRef = this.getEC('mainTable')
tableRef.refresh()
}
`
// Check if an external component exists and interact with it
const checkExternalComponent = () => {
if (vFormRef.value.hasEC('mainTable')) {
const table = vFormRef.value.getEC('mainTable')
table.doSomething()
}
}
```
--------------------------------
### Using the Form Renderer Component
Source: https://github.com/vform666/variant-form3-vite/blob/master/README.md
Implementation of the form renderer component to display forms and handle submission logic.
```vue
Submit
```
--------------------------------
### Designer Control and Export
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Utility methods to manage the designer state, including clearing the canvas, previewing the form, and exporting configurations to JSON, code, or SFC formats.
```javascript
const vfdRef = ref(null)
const clearForm = () => vfdRef.value.clearDesigner()
const preview = () => vfdRef.value.previewForm()
const exportJsonDialog = () => vfdRef.value.exportJson()
const exportCodeDialog = () => vfdRef.value.exportCode()
const generateSFCDialog = () => vfdRef.value.generateSFC()
```
--------------------------------
### Dynamically Load Form JSON
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Use setFormJson to update the form configuration at runtime, allowing for dynamic switching between different form layouts.
```javascript
const vFormRef = ref(null)
const loadFormFromServer = async () => {
const response = await fetch('/api/form/123')
const formJson = await response.json()
vFormRef.value.setFormJson(formJson)
}
```
--------------------------------
### Draggable with Transition Group
Source: https://github.com/vform666/variant-form3-vite/blob/master/lib/vuedraggable/README.md
Shows how to integrate the draggable component with Vue's transition-group for animated list reordering.
```html
{{element.name}}
```
--------------------------------
### Retrieve Form Widgets
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Methods to access all field or container widgets currently present in the designer. These return an array of objects containing type, name, and configuration details.
```javascript
const vfdRef = ref(null)
const getAllFields = () => {
const fieldWidgets = vfdRef.value.getFieldWidgets()
return fieldWidgets
}
const getAllContainers = () => {
const containerWidgets = vfdRef.value.getContainerWidgets()
return containerWidgets
}
```
--------------------------------
### Using the Form Designer Component
Source: https://github.com/vform666/variant-form3-vite/blob/master/README.md
Implementation of the visual form designer component within a Vue 3 template.
```vue
```
--------------------------------
### Load Form JSON into VFormDesigner (Vue)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Shows how to use the `setFormJson` method of the VFormDesigner component to load a form configuration. The configuration can be provided as a JavaScript object or a JSON string, enabling the editing of existing forms or loading templates.
```javascript
// 获取设计器引用
const vfdRef = ref(null)
// 加载表单 JSON(对象格式)
const formJsonObj = {
widgetList: [
{
type: 'input',
icon: 'text-field',
formItemFlag: true,
options: {
name: 'username',
label: '用户名',
labelWidth: null,
defaultValue: '',
placeholder: '请输入用户名',
columnWidth: '200px',
disabled: false,
hidden: false,
required: true,
requiredHint: '用户名不能为空',
validation: '',
validationHint: ''
}
},
{
type: 'select',
icon: 'select-field',
formItemFlag: true,
options: {
name: 'gender',
label: '性别',
defaultValue: '',
placeholder: '请选择性别',
optionItems: [
{ label: '男', value: 'male' },
{ label: '女', value: 'female' }
],
required: false
}
}
],
formConfig: {
modelName: 'formData',
refName: 'vForm',
labelWidth: 100,
labelPosition: 'left',
size: '',
layoutType: 'PC',
onFormCreated: '',
onFormMounted: '',
onFormDataChange: ''
}
}
vfdRef.value.setFormJson(formJsonObj)
// 也支持 JSON 字符串格式
const formJsonStr = JSON.stringify(formJsonObj)
vfdRef.value.setFormJson(formJsonStr)
```
--------------------------------
### Designer Widget Management
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Methods to retrieve field and container widgets from the VForm Designer instance.
```APIDOC
## GET /designer/widgets
### Description
Retrieves lists of all field or container widgets currently present in the designer.
### Method
METHOD CALL
### Endpoint
vfdRef.value.getFieldWidgets() / vfdRef.value.getContainerWidgets()
### Response
- **fieldWidgets** (Array) - List of objects containing type, name, and field configuration.
- **containerWidgets** (Array) - List of objects containing type, name, and container configuration.
```
--------------------------------
### VForm 3 Component Event Definitions
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Illustrates how to define event handlers for individual form components, such as input fields. This includes events like onCreated, onMounted, onInput, onChange, onFocus, onBlur, and onValidate. The onValidate event allows for custom validation logic using a callback function.
```javascript
// 输入框组件事件示例
const inputOptions = {
onCreated: `
console.log('输入框组件已创建')
`,
onMounted: `
console.log('输入框组件已挂载')
`,
onInput: `
// 参数: value
console.log('输入中:', value)
`,
onChange: `
// 参数: value
console.log('值已变更:', value)
`,
onFocus: `
// 参数: event
console.log('获得焦点')
`,
onBlur: `
// 参数: event
console.log('失去焦点')
`,
onValidate: `
// 参数: rule, value, callback
// 自定义验证逻辑
if (value && value.length < 3) {
callback(new Error('长度不能少于3个字符'))
} else {
callback()
}
`
}
```
--------------------------------
### Disable/Enable Entire Form (JavaScript)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Provides methods to disable or enable all components within a form. `disableForm()` effectively makes the form read-only, while `enableForm()` restores it to an editable state. Useful for managing overall form interactivity.
```javascript
const vFormRef = ref(null)
// 禁用整个表单(只读模式)
const setReadOnly = () => {
vFormRef.value.disableForm()
}
// 启用整个表单(编辑模式)
const setEditable = () => {
vFormRef.value.enableForm()
}
// 根据状态切换
const toggleFormState = (isEditable) => {
if (isEditable) {
vFormRef.value.enableForm()
} else {
vFormRef.value.disableForm()
}
}
```
--------------------------------
### VFormRender API
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Methods for interacting with the rendered form, including data retrieval, validation, and dynamic updates.
```APIDOC
## POST /render/form
### Description
Methods to manage the lifecycle and data of a rendered VForm instance.
### Methods
- `getFormData()`: Returns a Promise that resolves with validated form data or rejects with errors.
- `resetForm()`: Resets the form fields to their initial values.
- `setFormJson(json)`: Dynamically updates the form structure at runtime.
### Request Body
- **json** (Object/String) - The new form configuration schema.
```
--------------------------------
### Add Custom Container Component Schema in VForm 3
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Defines the JSON schema for a custom container component ('card') and details the process for loading it into the VForm designer. This includes registering both design-time and run-time versions of the component, defining its properties, and setting up property editors and code generators. Requires VForm's extension utilities.
```javascript
// card-schema.js - Define container component Schema
export const cardSchema = {
type: 'card',
category: 'container',
icon: 'card',
widgetList: [],
options: {
name: '',
label: 'card',
hidden: false,
folded: false,
showFold: true,
cardWidth: '100%',
shadow: 'hover',
customClass: ''
}
}
// Load container extension
import { addContainerWidgetSchema } from '@/components/form-designer/widget-panel/widgetsConfig'
import CardWidget from './card/card-widget' // Design-time component
import CardItem from './card/card-item' // Run-time component
import { registerCWGenerator } from '@/utils/sfc-generator'
export const loadContainerExtension = function (app) {
// 1. Load component JSON Schema
addContainerWidgetSchema(cardSchema)
// 2. Register design-time and run-time components
app.component(CardWidget.name, CardWidget)
app.component(CardItem.name, CardItem)
// 3. Register property editors
PERegister.registerCPEditor(app, 'card-folded', 'card-folded-editor',
PEFactory.createBooleanEditor('folded', 'extension.setting.cardFolded'))
PERegister.registerCPEditor(app, 'card-cardWidth', 'card-cardWidth-editor',
PEFactory.createInputTextEditor('cardWidth', 'extension.setting.cardWidth'))
// 4. Register code generator
registerCWGenerator('card', cardTemplateGenerator)
}
```
--------------------------------
### Add Custom Field Component Schema in VForm 3
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Defines the JSON schema for a custom field component ('alert') and outlines the process for loading it into the VForm designer. This involves defining the component's properties, registering it globally, and setting up property editors and code generators. Requires VForm's extension utilities.
```javascript
// extension-schema.js - Define component Schema
export const alertSchema = {
type: 'alert',
icon: 'alert',
formItemFlag: false,
options: {
name: '',
title: '',
type: 'info',
description: '',
closable: true,
closeText: '',
center: false,
showIcon: false,
effect: 'light',
hidden: false,
onCreated: '',
onMounted: '',
onClose: ''
}
}
// extension-loader.js - Load extension component
import { addCustomWidgetSchema } from '@/components/form-designer/widget-panel/widgetsConfig'
import * as PERegister from '@/components/form-designer/setting-panel/propertyRegister'
import * as PEFactory from '@/components/form-designer/setting-panel/property-editor-factory.jsx'
import AlertWidget from './alert/alert-widget' // Assuming AlertWidget is defined elsewhere
import { registerFWGenerator } from '@/utils/sfc-generator'
import { alertTemplateGenerator } from './extension-sfc-generator' // Assuming generator is defined elsewhere
export const loadExtension = function (app) {
// 1. Load component JSON Schema
addCustomWidgetSchema(alertSchema)
// 2. Globally register the component
app.component(AlertWidget.name, AlertWidget)
// 3. Register property editors
PERegister.registerCPEditor(app, 'alert-title', 'alert-title-editor',
PEFactory.createInputTextEditor('title', 'extension.setting.alertTitle'))
const typeOptions = [
{ label: 'success', value: 'success' },
{ label: 'warning', value: 'warning' },
{ label: 'info', value: 'info' },
{ label: 'error', value: 'error' }
]
app.component('alert-type-editor',
PEFactory.createSelectEditor('type', 'extension.setting.alertType',
{ optionItems: typeOptions }))
// 4. Register code generator
registerFWGenerator('alert', alertTemplateGenerator)
}
```
--------------------------------
### Component Usage:
Source: https://github.com/vform666/variant-form3-vite/blob/master/lib/vuedraggable/README.md
The primary component for enabling drag-and-drop functionality on a list of items.
```APIDOC
## [COMPONENT]
### Description
The `` component wraps a list of items to enable drag-and-drop reordering. It synchronizes the visual order with the underlying data array.
### Parameters
#### Props
- **v-model** (Array) - Required - The data array to be synchronized.
- **item-key** (String) - Required - The unique key property for each item in the list.
- **group** (String/Object) - Optional - Defines the drag group for cross-list dragging.
- **tag** (String) - Optional - The HTML tag or component to render (e.g., 'transition-group').
#### Slots
- **item** - Required - Scoped slot to render each list item. Receives {element, index}.
- **header** - Optional - Content rendered before the list.
- **footer** - Optional - Content rendered after the list.
### Usage Example
{{element.name}}
```
--------------------------------
### Reset Form (JavaScript)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Resets the entire form to its initial state. This action clears all field values and removes any validation states, preparing the form for a new input cycle.
```javascript
const vFormRef = ref(null)
// 重置表单
const resetForm = () => {
vFormRef.value.resetForm()
console.log('表单已重置')
}
```
--------------------------------
### Reload Option Data in VForm 3
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Demonstrates how to reload option data for dropdowns, radio buttons, and other select components in VForm 3. This can be done for a single component, multiple components, or all components at once. It requires a VForm instance reference.
```javascript
const vFormRef = ref(null)
const optionData = reactive({})
// Update option data and reload
const updateCityOptions = async (provinceCode) => {
const response = await fetch(`/api/cities?province=${provinceCode}`)
const cities = await response.json()
optionData.city = cities.map(c => ({
label: c.name,
value: c.code
}))
// Reload options for a specific component
vFormRef.value.reloadOptionData('city')
}
// Reload options for multiple components
const reloadMultipleOptions = () => {
vFormRef.value.reloadOptionData(['city', 'district', 'street'])
}
// Reload all option components
const reloadAllOptions = () => {
vFormRef.value.reloadOptionData() // Reloads all if no argument is passed
}
```
--------------------------------
### Change Language in VForm 3
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Demonstrates how to change the display language of the VForm renderer using the `changeLanguage` method. This allows for internationalization of the form. It requires a VForm instance reference and a valid language code string.
```javascript
const vFormRef = ref(null)
// Switch to English
const switchToEnglish = () => {
vFormRef.value.changeLanguage('en-US')
}
// Switch to Chinese
const switchToChinese = () => {
vFormRef.value.changeLanguage('zh-CN')
}
```
--------------------------------
### Disable/Enable Widgets (JavaScript)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Allows disabling or enabling specified form components. Supports targeting individual components by name or multiple components using an array of names. Includes conditional disabling/enabling based on user roles or other logic.
```javascript
const vFormRef = ref(null)
// 禁用单个组件
const disableSingle = () => {
vFormRef.value.disableWidgets('email')
}
// 禁用多个组件
const disableMultiple = () => {
vFormRef.value.disableWidgets(['email', 'phone', 'address'])
}
// 启用组件
const enableWidgets = () => {
vFormRef.value.enableWidgets(['email', 'phone', 'address'])
}
// 根据条件禁用
const handleRoleChange = (role) => {
if (role === 'viewer') {
vFormRef.value.disableWidgets(['name', 'email', 'phone'])
} else {
vFormRef.value.enableWidgets(['name', 'email', 'phone'])
}
}
```
--------------------------------
### VForm 3 Form Lifecycle Events Configuration
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Defines event handler functions within the form configuration for lifecycle hooks like onFormCreated, onFormMounted, and onFormDataChange. These functions allow custom logic execution at different stages of the form's existence. The 'this' context within these handlers refers to the VFormRender instance.
```javascript
const formConfig = {
// 表单创建后触发
onFormCreated: `
console.log('表单已创建')
// this 指向 VFormRender 实例
`,
// 表单挂载后触发
onFormMounted: `
console.log('表单已挂载')
// 可以在这里初始化数据
this.setFieldValue('createTime', new Date().toISOString())
`,
// 表单数据变更时触发
onFormDataChange: `
// 参数: fieldName, newValue, oldValue, formModel, subFormName, subFormRowIndex
console.log('字段', fieldName, '从', oldValue, '变更为', newValue)
// 字段联动示例
if (fieldName === 'province') {
this.setFieldValue('city', '')
}
`
}
```
--------------------------------
### Validate Form (JavaScript)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Manually triggers form validation. A callback function is provided to handle the validation result, indicating whether the form is valid or not. This is typically used before submitting form data.
```javascript
const vFormRef = ref(null)
// 验证表单
const validate = () => {
vFormRef.value.validateForm((valid) => {
if (valid) {
console.log('表单验证通过')
// 执行提交操作
} else {
console.log('表单验证失败')
}
})
}
```
--------------------------------
### Clear Validation Status (JavaScript)
Source: https://context7.com/vform666/variant-form3-vite/llms.txt
Clears the validation status for the entire form or for specific fields. This can be useful when re-validating or resetting user feedback on input errors.
```javascript
const vFormRef = ref(null)
// 清除所有验证状态
const clearAllValidation = () => {
vFormRef.value.clearValidate()
}
// 清除指定字段的验证状态
const clearFieldValidation = () => {
vFormRef.value.clearValidate(['name', 'email'])
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.