Skip to content

Commit

Permalink
fix(vue): fix useFormEffects not reactive when form change (#3371)
Browse files Browse the repository at this point in the history
  • Loading branch information
frehaiku authored Sep 5, 2022
1 parent af1484e commit b8b4c51
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 6 deletions.
47 changes: 46 additions & 1 deletion packages/vue/src/__tests__/field.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Vue, { FunctionalComponentOptions } from 'vue'
import { render, fireEvent, waitFor } from '@testing-library/vue'
import { defineComponent, h } from '@vue/composition-api'
import { defineComponent, h, ref } from '@vue/composition-api'
import {
createForm,
Field as FieldType,
Expand Down Expand Up @@ -311,6 +311,51 @@ test('useFormEffects', async () => {
})
})

test('useFormEffects: should be reregister when formRef change', async () => {
const CustomField = defineComponent({
setup() {
const reactiveText = ref()
useFormEffects(() => {
onFieldChange('aa', ['value'], (target) => {
if (isVoidField(target)) return
reactiveText.value = target.value
})
})
return () =>
h('div', { attrs: { 'data-testid': 'custom-value' } }, [
reactiveText.value,
])
},
})

const { queryByTestId } = render({
setup() {
const formRef = ref(createForm())
return {
formRef,
Input,
CustomField,
changeForm() {
// form change
formRef.value = createForm()
formRef.value.setValues({ aa: 'text' })
},
}
},
template: `<FormProvider :form="formRef">
<Field name="aa" :decorator="[Decorator]" :component="[Input]" />
<VoidField name="bb" :component="[CustomField]" />
<button data-testid="btn" @click="changeForm()">Change</button>
</FormProvider>`,
})

expect(queryByTestId('custom-value').textContent).toEqual('')
queryByTestId('btn').click()
await waitFor(() => {
expect(queryByTestId('custom-value').textContent).toEqual('text')
})
})

test('connect', async () => {
const CustomField = connect(
{
Expand Down
14 changes: 9 additions & 5 deletions packages/vue/src/hooks/useFormEffects.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import { onBeforeUnmount } from 'vue-demi'
import { onBeforeUnmount, watchEffect } from 'vue-demi'
import { Form } from '@formily/core'
import { uid } from '@formily/shared'
import { useForm } from './useForm'

export const useFormEffects = (effects?: (form: Form) => void): void => {
const formRef = useForm()

const id = uid()
formRef.value.addEffects(id, effects)
const stop = watchEffect((onCleanup) => {
const id = uid()
formRef.value.addEffects(id, effects)

onBeforeUnmount(() => {
formRef.value.removeEffects(id)
onCleanup(() => {
formRef.value.removeEffects(id)
})
})

onBeforeUnmount(() => stop())
}

0 comments on commit b8b4c51

Please sign in to comment.