项目中很多场景都有新增和编辑,使用一个dialog完成两个功能
新增和编辑分开写就上下面这样,写两个dialog
<!--添加角色对话框-->
<el-dialog
title="添加角色"
:visible.sync="addRoleDialogVisible"
width="30%">
<el-form ref="form" :model="roleData" :rules="addRoleRules" label-width="0px">
<el-form-item label="" prop="roleName">
<el-input v-model="roleData.roleName" prefix-icon="el-icon-user"></el-input>
</el-form-item>
<el-form-item label="" prop="roleDesc">
<el-input v-model="roleData.roleDesc" prefix-icon="el-icon-info"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="addRoleDialogVisible = false">取 消</el-button>
<el-button type="primary" @click="createRole">确 定</el-button>
</span>
</el-dialog>
<!--编辑角色对话框-->
<el-dialog
title="编辑用户"
:visible.sync="editRoleDialogVisible"
width="30%">
<el-form ref="form" :model="editData" :rules="addRoleRules" label-width="0px">
<el-form-item label="" prop="roleName">
<el-input v-model="editData.roleName" prefix-icon="el-icon-user"></el-input>
</el-form-item>
<el-form-item label="" prop="roleDesc">
<el-input v-model="editData.roleDesc" prefix-icon="el-icon-info"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="editRoleDialogVisible = false">取 消</el-button>
<el-button type="primary" @click="editRole">确 定</el-button>
</span>
</el-dialog>
但是当el-dialog中的内容很多时,不仅代码量double,而且两个差不多的代码写两遍有什么意思???
解决方法:使用一个dialog完成新增和编辑
思路:vue组件的data中增加一个hasId(hasId用于区分新增和编辑,新增的时候还没有id,编辑的时候要通过id去获取具体数据)
效果:
上代码:
点击新增按钮
handleAdd(){
this.roleDialogVisible = true;
this.hasId = "";
//重置表单数据resetField方法
this.$nextTick(()=>{
this.$refs.roleForm.resetFields();
//重置表单数据
this.roleForm = {
roleCode:'',
roleName:'',
roleType:'',
status:1,
roleDesc:''
};
});
},
点击编辑按钮
handleEdit(row){
this.roleDialogVisible = true;
this.hasId = row.roleId;
//重置表单数据
this.roleForm.roleName = row.roleName;
this.roleForm.roleId = row.roleId;
this.roleForm.roleCode = row.roleCode;
this.roleForm.roleType = row.roleType;
this.roleForm.status = row.status;
this.roleForm.roleDesc = row.roleDesc;
},
点击保存按钮时判断一下是新增还是编辑去调用对应的方法
save(){
this.$refs.roleForm.validate((valid) => {
if (valid && this.hasId) {//编辑
updateRoleInfo(this.roleForm)
.then(response=>{
if(response.succ === 'ok'){
this.$message.success(response.msg);
this.roleDialogVisible = false;
this.getRoleList();
}
})
}else if(valid && !this.hasId) {//新增
addRole(this.roleForm)
.then(response=>{
if(response.succ === 'ok'){
this.$message.success(response.msg);
this.roleDialogVisible = false;
this.getRoleList();
}
})
} else {
return false;
}
});
},