1. 重复操作时清空值
// 选中表格复选框
handleSelectChange(selection, row) {
this.selectArr.length = 0; // 注意清空语句
selection.forEach((item, index) => {
const { ssh_ip, ssh_node_type } = item;
this.selectArr.push({
ssh_ip,
ssh_node_type
});
});
console.log(this.selectArr);
}
不加数组清空语句,踩坑:
例如,选中表格两项时,打印语句的数组长度为3,并不是预期的长度2。因为重复触发了选中事件,勾选第一项时一条,勾选第二项时变成了两条,会重复push之前选中项的内容。
2. 动态判断选中值唯一
判断下拉框选中事件 值不重复
if (this.fieldArr.indexOf(val) !== -1) // 选中val,fieldArr 中必然添加该值,永远 !== -1
if (this.fieldArr.indexOf(val) !== this.fieldArr.lastIndexOf(val))
// 判断val第一次出现位置与最后一次出现位置,如果值相等表示只出现一次
3. 编辑时,根据列表数据校验值是否重复
容易出现误区: 在添加/编辑中,根据列表已有数据对某项值进行重复校验,如‘名称’。编辑时因为数据回显,不能直接用includes()等方法直接判断,因为列表数据中已包含当前值。
思路:可以单独保存编辑回显时的原始值,在数组基础上过滤掉该原始值再进行判断。
const { title } = this.sceneForm; // 解构
const tmpSceneData = [];
this.sceneList.map(item => {
if (item.title !== this.originTitle) tmpSceneData.push(item); // 过滤原始值
});
if (tmpSceneData.length) {
const checkSceneName = tmpSceneData.every(item => item.title !== title); // 判断重复
if (!checkSceneName) {
this.$message.warning('场景名称不能重复!');
return;
}
}
4. 清除脏数据
const { code, data } = res;
if (code === 200) {
this.tableData = data.result;
this.total = data.total;
}
this.tableData = data.result.map(item => {
item.max_time = item.max_time && '';
item.source = item.source && '';
return item;
})
5. push 赋值
this.operation = res.data.push('Apple', 'Android'); // 直接这样写赋值有问题 返回的是新数组长度
res.data.push('Apple', 'Android');
this.operation = res.data
6. 关闭弹窗时清空表单数据
需求:在关闭弹窗时清空表单数据
问题:表单数据结构两层以上时,深层数据清空存在问题
props: {
commonParams: {
type: Object,
default: () => {}
}
},
// data
sceneForm: {
title: '', // 标题
describe: '', // 描述
'data_type': 0, // 0 新增场景, 1 新增风险类型
'risk_type': '', // 场景类型
'scene_level': 0, // 场景等级
content: {
ip: '',
tproto: '',
port: '',
...
belong: []
},
originTitle: '', // 场景名称原始值
type: 1 // 1 新增,2 编辑
}
// 初始化数据
initSceneInfo() {
this.isDisplay = true;
this.sceneTitle = this.commonParams.type === 2 ? '编辑场景' : '添加场景';
if (this.commonParams.type === 2) {
this.sceneForm = JSON.parse(JSON.stringify(this.commonParams));
} else {
this.resetParams(); //判断添加 清除弹窗上次数据
}
},
// 关闭弹窗
closeDialog() {
if (this.commonParams.type === 2) {
this.sceneForm = JSON.parse(JSON.stringify(this.commonParams)); // 拷贝
} else {
this.resetParams();
}
this.$emit('closeDialog', false);
},
// 重置
resetParams() {
this.sceneForm['data_type'] = 0;
this.sceneForm['risk_type'] = '';
this.sceneForm['title'] = '';
this.sceneForm['scene_level'] = 0;
this.sceneForm['describe'] = '';
for (const property in this.sceneForm.content) {
this.$set(this.sceneForm.content, property, ''); // 可以引申学习this.$set的用法
}
},