刚接触 vue3,想弹框,点确认调接口添加信息,然后数据清空,使用 reactive 定义的变量,修改变量时遇到点小问题,总结下:
定义变量
部分代码 <template> <el-dialog title="添加" v-model="open" append-to-body> <el-form label-width="68px"> <el-form-item label="name" prop="name"> <el-input v-model="testForm.name"> </el-input> </el-form-item> <el-form-item label="age" prop="age"> <el-input v-model="testForm.age"> </el-input> </el-form-item> </el-form> <template #footer> <span class="dialog-footer"> <el-button type="primary" @click="createUnit"> 确认 </el-button> <el-button @click="open = false">取消</el-button> </span> </template> </el-dialog> </template> <script setup > let testForm = reactive({ name: "", age: null, }); </script >
复制
修改变量
function createUnit() { open.value = false; testForm = { name: "", age: null, }; } 或者 function createUnit() { open.value = false; testForm = reactive({ name: "", age: null, }); }
复制
想像vue2 一样给 testForm 重新赋值,结果表单里面是数据没清掉,表单内容还修改不了了
解决办法
1.各个属性单独赋值
function createUnit() { open.value = false; testForm.name = ""; testForm.age = null; }
复制
2.使用 Object.assign
function createUnit() { open.value = false; testForm = Object.assign(testForm, { name: "", age: null, }); }
复制
如果定义对象的属性比较多,可以定义一个函数,需要重新赋值的地方调用这个函数。
function createUnit() { open.value = false; reset(); } function reset() { testForm.name = ""; testForm.age = null; testForm.a = ""; testForm.b = ""; testForm.c = ""; testForm.d = ""; }
复制
如果大家有好的重新赋值的方法,还请指点。