ref结合作用域插槽实现父组件触发子组件表单方法
具体场景:
比如表单封装
父组件在进行提交操作时 触发子组件表单方法
子组件就需要用到ref结合作用域插槽将表单实例form和表单数据对象model传出去
子组件当中的内容:
html内容
<el-form ref="form">...</el-form>
html内容:form、model通过作用域插槽分发出去
...
<el-form-item>
<slot name="action" :form="form" :model="model"></slot>
</el-form-item>
...
js内容:FormInstance类型从element-plus中引用
const form = ref<FormInstance | null>()
父组件中的内容:
html内容:#action="scope"
<template #action="scope">
<el-button type="primary" @click="submitForm(scope)">新增</el-button>
<el-button @click="resetForm(scope)">重置</el-button>
</template>
js内容:使用 scope.form、scope.model拿到父组件表单实例以及表单数据
const submitForm = (scope: Scope) => {
scope.form.validate((valid) => {
if (valid) {
} else {
ElMessage.error("填写有误,请检查");
}
});
};
const resetForm = (scope: Scope) => {
scope.form.resetFields();
};