Skip to content

Commit

Permalink
feat fix initValues
Browse files Browse the repository at this point in the history
  • Loading branch information
v_huyilin committed Nov 27, 2024
1 parent e8ae079 commit 9193f9a
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 51 deletions.
7 changes: 5 additions & 2 deletions packages/components/FormItem.vue
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
</template>

<script setup lang="ts">
import { computed, onMounted, reactive } from 'vue'
import { computed, onBeforeMount, reactive } from 'vue'
import { isRegexString, getDataByPath, setDataByPath, ns } from '@vue-form-craft/utils'
import type { FormItemType } from '@vue-form-craft/types'
import Icon from '@vue-form-craft/icons'
Expand Down Expand Up @@ -180,14 +180,17 @@ const formItemProps = computed(() => {
return props
})
onMounted(() => {
onBeforeMount(() => {
if (value.value === undefined && thisProps.initialValue !== undefined && !formInstance.design) {
const newInitialValues = setDataByPath(
formInstance.initialValues,
thisProps.name,
thisProps.initialValue
)
formInstance.updateInitialValues(newInitialValues)
value.value = thisProps.initialValue
}
})
</script>
26 changes: 19 additions & 7 deletions packages/elements/FormList/FormList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
</el-space>

<el-button
v-if="allowReduce"
v-if="allowReduce && !isMin"
@click="handleReduceItem(index)"
circle
type="primary"
Expand All @@ -37,7 +37,7 @@
<div class="card-header">
<span>{{ title + (index + 1) }}</span>
<el-button
v-if="allowReduce"
v-if="allowReduce && !isMin"
@click="handleReduceItem(index)"
circle
type="primary"
Expand Down Expand Up @@ -71,7 +71,7 @@
<el-table-column fixed="right" min-width="60">
<template #default="record">
<el-button
v-if="allowReduce"
v-if="allowReduce && !isMin"
@click="handleReduceItem(record.$index)"
circle
type="primary"
Expand Down Expand Up @@ -105,7 +105,7 @@
</template>

<script setup lang="ts">
import { computed, h, provide, ref, watch } from 'vue'
import { computed, h, onMounted, provide, ref, watch } from 'vue'
import { FormItem, CanvasGroup } from '@vue-form-craft/components'
import { deepParse } from '@vue-form-craft/utils'
import { isEqual, isString, pickBy } from 'lodash'
Expand All @@ -118,10 +118,10 @@ interface Props {
children: FormItemType[]
allowAdd?: boolean
allowReduce?: boolean
minLines?: number
maxLines?: number
mode?: 'table' | 'card' | 'inline'
title?: string
newItemDefaults?: (index: number) => Record<string, any>
name?: string
disabled?: boolean
}
Expand All @@ -130,10 +130,10 @@ const props = withDefaults(defineProps<Props>(), {
children: () => [],
allowAdd: true,
allowReduce: true,
minLines: 0,
maxLines: 999,
mode: 'table',
title: '',
newItemDefaults: () => ({}),
name: ''
})
Expand All @@ -150,11 +150,15 @@ const isMax = computed(() => {
return list.value.length >= props.maxLines
})
const isMin = computed(() => {
return list.value.length <= props.minLines
})
const handleAddItem = () => {
if (isMax.value) {
return
}
list.value = [...list.value, props.newItemDefaults(list.value.length)]
list.value = [...list.value, {}]
}
const handleReduceItem = (index: number) => {
Expand All @@ -176,6 +180,8 @@ const formatter = (row: any, column: TableColumnCtx<any>, cellValue: any, index:
// formList 值联动
watch(list, (newVal, oldVal) => {
// console.log(newVal, oldVal);
const changeIndex = newVal.reduce((acc, cur, index) => {
if (!isEqual(cur, oldVal[index])) {
acc = index
Expand Down Expand Up @@ -211,6 +217,12 @@ watch(list, (newVal, oldVal) => {
})
})
onMounted(() => {
if (props.minLines && !list.value?.length) {
list.value = Array.from({ length: props.minLines }, () => ({}))
}
})
provide(
'$objGroupBase',
computed(() => `${props.name}.${cIndex.value}`)
Expand Down
31 changes: 22 additions & 9 deletions packages/elements/FormList/attrSchema.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { FormSchema } from "@vue-form-craft/types";
import type { FormSchema } from '@vue-form-craft/types'

export default {
size: 'small',
Expand All @@ -7,7 +7,12 @@ export default {
label: '自增容器',
children: [],
props: {
mode: 'table'
mode: 'table',
title: '数据',
minLines: 0,
maxLines: 999,
allowAdd: true,
allowReduce: true
}
},
items: [
Expand Down Expand Up @@ -39,8 +44,7 @@ export default {
'column-gap': 20
},
designKey: 'form-R003',
name: 'cNmCuu',

name: 'cNmCuu'
},
{
label: '显示模式',
Expand All @@ -56,12 +60,21 @@ export default {
}
},
{
label: '卡片标题',
label: '自增前缀',
component: 'Input',
name: 'props.title',
hidden: "{{$values.props.mode!=='card'}}"
name: 'props.title'
},


{
label: '最小行数',
component: 'InputNumber',
name: 'props.minLines'
},
{
label: '最大行数',
component: 'InputNumber',
name: 'props.maxLines'
},
{ label: '允许新增行', component: 'Switch', name: 'props.allowAdd' },
{ label: '允许删除行', component: 'Switch', name: 'props.allowReduce' }
]
} satisfies FormSchema
34 changes: 14 additions & 20 deletions packages/form-render/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
</template>

<script setup lang="ts">
import { ref, computed, reactive, provide, watch, nextTick, toRefs, readonly } from 'vue'
import { ref, computed, reactive, provide, watch, nextTick, toRefs, readonly, onMounted } from 'vue'
import type { FormInstance as ElFormInstance } from 'element-plus'
import { handleLinkages, deepParse, setDataByPath, getDataByPath } from '@vue-form-craft/utils'
import { cloneDeep, merge } from 'lodash'
import { cloneDeep } from 'lodash'
import type { FormInstance, FormRenderProps, FormSchema } from '@vue-form-craft/types'
import { $formInstance } from '@vue-form-craft/config/symbol'
import { useLocale } from '@vue-form-craft/hooks'
Expand All @@ -43,7 +43,7 @@ const emit = defineEmits<{
const formRef = ref<ElFormInstance>()
const formValues = defineModel<Record<string, any>>({ default: () => ({}) })
const formValues = defineModel<Record<string, any>>({ default: reactive({}) })
const schema = defineModel<FormSchema>('schema', {
default: reactive({
Expand Down Expand Up @@ -84,32 +84,25 @@ const context = computed(() => ({
}))
watch(
formValues,
() => cloneDeep(formValues.value),
async (newVal, oldVal) => {
if (props.read) {
return
}
await nextTick()
setTimeout(() => {
handleLinkages({ newVal, oldVal, formValues, formItems: formItems.value })
})
handleLinkages({ newVal, oldVal, formValues, formItems: formItems.value,updateFormValues })
},
{ deep: true, immediate: true }
)
watch(
() => props.schema?.initialValues,
async (newVal) => {
await nextTick()
Object.assign(initialValues, cloneDeep(newVal))
},
{ immediate: true }
)
watch(initialValues, async (newVal) => {
await nextTick()
formValues.value = merge(newVal, formValues.value)
// 支持从schema初始化默认值对象
onMounted(() => {
if (props.schema?.initialValues) {
const initialValues = cloneDeep(props.schema?.initialValues)
// 暂时使用浅合并,可能会造成原默认值props会被当前props永久覆盖
formValues.value = Object.assign(initialValues, formValues.value)
}
})
const validate: FormInstance['validate'] = () => formRef.value?.validate()
Expand All @@ -126,6 +119,7 @@ const submit: FormInstance['submit'] = () => {
const resetFields: FormInstance['resetFields'] = (names) => {
emit('reset')
if (names) {
let temp = cloneDeep(formValues.value)
names.forEach((name) => {
Expand All @@ -138,7 +132,7 @@ const resetFields: FormInstance['resetFields'] = (names) => {
}
const updateFormValues: FormInstance['updateFormValues'] = (values) => {
formValues.value = values
Object.assign(formValues.value, values)
}
const updateSelectData: FormInstance['updateSelectData'] = (key, value) => {
Expand Down
16 changes: 12 additions & 4 deletions packages/utils/handleLinkages.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { isEqual, cloneDeep, isArray } from 'lodash'
import type { FormItemType } from '@vue-form-craft/types'
import type { FormInstance, FormItemType } from '@vue-form-craft/types'
import setDataByPath from './setDataByPath'
import getDataByPath from './getDataByPath'

Expand All @@ -8,9 +8,16 @@ type handleLinkagesType = (obj: {
oldVal?: Record<string, any>
formValues: Record<string, any>
formItems: FormItemType[]
updateFormValues: FormInstance['updateFormValues']
}) => void

const handleLinkages: handleLinkagesType = ({ newVal, oldVal={}, formValues, formItems }) => {
const handleLinkages: handleLinkagesType = ({
newVal,
oldVal = {},
formValues,
formItems,
updateFormValues
}) => {
for (const item of formItems) {
const newValue = getDataByPath(newVal, item.name)
const oldValue = getDataByPath(oldVal, item.name)
Expand Down Expand Up @@ -42,15 +49,16 @@ const handleLinkages: handleLinkagesType = ({ newVal, oldVal={}, formValues, for
}
}
})
formValues.value = temp
updateFormValues(temp)
}

if (item.children && item.component !== 'FormList') {
handleLinkages({
newVal,
oldVal,
formValues,
formItems: item.children
formItems: item.children,
updateFormValues
})
}
}
Expand Down
28 changes: 19 additions & 9 deletions packages/utils/setDataByPath.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,39 @@
import { cloneDeep } from 'lodash'

const setDataByPath = (object: Record<string,any>, path: string, value: any) => {
const setDataByPath = (object: Record<string, any>, path: string, value: any) => {
// 深拷贝对象,避免直接修改原对象
const cloneObj = cloneDeep(object)

// 将路径字符串分割成路径数组
const pathArray = path.split('.')

// 递归函数,用于在对象的深层级找到要修改的位置并更新其值
function update(obj: Record<string,any>, pathArray: string[], value: any) {
function update(obj: Record<string, any>, pathArray: string[], value: any) {
// 如果路径数组为空,表示已经到达了最后一级,更新值并返回
if (pathArray.length === 1) {
obj[pathArray[0]] = value
return
}

// 获取当前路径的第一个部分
const currentKey = pathArray.shift()
const currentKey = pathArray[0]

// 下一级路径
const nextKey = pathArray[1]

if (currentKey) {
// 如果当前键不存在,则创建一个空对象
if (!obj[currentKey]) {
// 如果当前键不存在,则创建一个空对象/空数组
if (!obj[currentKey]) {
if (!isNaN(Number(nextKey))) {
// 如果下一级是数字路径,则创建一个空数组
obj[currentKey] = []
} else {
// 否则创建一个空对象
obj[currentKey] = {}
}

// 递归调用更新函数
update(obj[currentKey], pathArray, value)
}

// 递归调用更新函数
update(obj[currentKey], pathArray.slice(1), value)
}

// 调用递归函数
Expand Down

0 comments on commit 9193f9a

Please sign in to comment.