From b8b4c5107e604dcbebcba8fff17577ef2906c514 Mon Sep 17 00:00:00 2001 From: frehkxu Date: Mon, 5 Sep 2022 22:23:36 +0800 Subject: [PATCH] fix(vue): fix useFormEffects not reactive when form change (#3371) --- packages/vue/src/__tests__/field.spec.ts | 47 +++++++++++++++++++++++- packages/vue/src/hooks/useFormEffects.ts | 14 ++++--- 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/packages/vue/src/__tests__/field.spec.ts b/packages/vue/src/__tests__/field.spec.ts index 64cc4b3570d..fd1188c18c2 100644 --- a/packages/vue/src/__tests__/field.spec.ts +++ b/packages/vue/src/__tests__/field.spec.ts @@ -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, @@ -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: ` + + + + `, + }) + + expect(queryByTestId('custom-value').textContent).toEqual('') + queryByTestId('btn').click() + await waitFor(() => { + expect(queryByTestId('custom-value').textContent).toEqual('text') + }) +}) + test('connect', async () => { const CustomField = connect( { diff --git a/packages/vue/src/hooks/useFormEffects.ts b/packages/vue/src/hooks/useFormEffects.ts index 5df17848207..2ef9d5c1222 100644 --- a/packages/vue/src/hooks/useFormEffects.ts +++ b/packages/vue/src/hooks/useFormEffects.ts @@ -1,4 +1,4 @@ -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' @@ -6,10 +6,14 @@ 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()) }