高质量网站外链建设大揭秘吐鲁番市建设局网站
Vue3 | Element Plus resetFields不生效
1. 简介
先打开创建对话框没有问题,但只要先打开编辑对话框,后续在打开对话框就会有默认值,还无法使用resetFields()重置。
 下面是用来复现问题的示例代码和示例GIF。
<script setup>
import {ref} from 'vue'const formRef = ref(null)
const dialogFormVisible = ref(false)
const title = ref('')
const formData = ref({username: null,password: null,
})const createDialog = () => {title.value = '创建'dialogFormVisible.value = true
}const resetDialog = () => {formRef.value.resetFields()
}const editDialog = () => {title.value = '编辑'// 模拟待编辑数据let user = {'username': 'yimtcode','password': '123456'}Object.assign(formData.value, user)dialogFormVisible.value = true
}const closeDialog = () => {formRef.value.resetFields()dialogFormVisible.value = false
}
</script><template><el-dialog :title="title" v-model="dialogFormVisible" :before-close="closeDialog"><el-form ref="formRef" :model="formData"><el-form-item label="username" prop="username"><el-input v-model="formData.username" autocomplete="off"></el-input></el-form-item><el-form-item label="password" prop="password"><el-input v-model="formData.password" autocomplete="off"></el-input></el-form-item></el-form><template #footer><span class="dialog-footer"><el-button @click="resetDialog">reset</el-button><el-button @click="dialogFormVisible = false">取 消</el-button><el-button type="primary" @click="dialogFormVisible = false">确 定</el-button></span></template></el-dialog><el-button @click="createDialog">create</el-button><el-button @click="editDialog">edit</el-button>
</template><style scoped>
</style>
 

2. 原因
前置知识:el-form会记录第一次打开的值,当作表单的默认值。在后续调用resetFields会将当前绑定的数据对象设置为el-form默认值。
editDialogtitle.value = '编辑'Object.assign(formData.value, user)dialogFormVisible.value = true:⭐️注意此时el-form将第一次打开的formValue值当成默认值也就是user对象的值。
closeDialogformRef.value.resetFields():⭐️此处重置是有问题,会将当前formData值重置为user对象的值,因为当前el-form默认值在上面已经变成了user。dialogFormVisible.value = falseu
createDialog打开对话框时,el-form就会将上面user当成默认值。
3. 解决方法
- 先让编辑对话框显示,完成
el-form初始化,防止将当前user信息当成默认值,影响createDialog。 - 在下一个DOM更新,在把数据更新上已经显示的对话框。
 
const editDialog = () => {title.value = '编辑'dialogFormVisible.value = truenextTick(() => {// 模拟待编辑数据let user = {'username': 'yimtcode','password': '123456'}Object.assign(formData.value, user)})
}
 
4. 参考
- resetFields重置初始值不生效的原因
 
