富文本组件 非Element Plus表单组件 自定义组件 触发表单校验

    项目中有很多自己封装的组件,如富文本组件,文件上传,图片上传等。而这些组件在表单中常常会在新增和编辑的场景应用。而且Element Plus官网展示demo都是基于Element Plus表单组件的,并没有演示非Element Plus表单组件,下面代码将演示如何实现非Element Plus的Vue组件触发ElForm的表单校验

自定义组件代码: ax-input-test.vue
<template>
    <input v-model="value" placeholder="请输入">
</template>
<script lang="ts">
import { computed } from 'vue'
import { useFormItem } from 'element-plus'
export default {
  name: "ax-input-test",
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue'],
  setup(props: any, { emit}) {
    const { formItem } = useFormItem()
    const value = computed({
        get() {
            return props.modelValue
        },
        set(val) {
            emit('update:modelValue', val)
            formItem?.validate('blur')
        }
    })
    return {
        value
    }
  }
}
</script>

使用组件的代码edit-user-confirm.vue

<template>
            <div class="body">
                <el-form
                    ref="formRef"
                    :model="userForm"
                    label-width="120px"
                    :rules="formRules"
                >
                    <el-form-item label="昵称:" prop="nickName">
                        <ax-input-test
                            class="content-input"
                            v-model="userForm.nickName"
                            placeholder="请输入您的昵称"
                        ></ax-input-test>
                    </el-form-item>
                    <div class="bottom-box">
                        <div class="btn-box">
                            <el-button type="primary" @click="onSubmit(formRef)">确认</el-button>
                        </div>
                    </div>
                </el-form>
            </div>
</template>

<script lang="ts">
import {reactive, ref, defineComponent} from 'vue';
import AxInputTest from '@/components/ax-input-test.vue'
export default defineComponent({
    name: "edit-user-confirm",
    components: {
        AxInputTest
    },
    emits: ['closeConfirm', 'saved'],
    setup(props, {emit}) {
        const formRules = reactive({
            nickName: [
                {
                    required: true,
                    message: '昵称不能为空',
                    trigger: 'blur',
                }
            ]
        });
        const userForm = reactive({
            nickName: ''
        });
        const onSubmit = (formRef) => {
            formRef.validate((valid) => {
                if (valid) {
                    //保存数据到接口
                }
            });
        };
        // 取消
        const onCancel = () => {
            emit('closeConfirm');
        }
        const formRef = ref(null);
        return {
            userForm,
            formRules,
            onSubmit,
            formRef,
            onCancel
        }
    }
})
</script>

 

posted @ 2022-11-16 11:46  王阿灿  阅读(693)  评论(0编辑  收藏  举报