Vue: 后台给出多选、单选混合 怎么解决?
在项目中遇到一个这样的问题,一个表单中有多选和单选,并且其中或许还会有 others 选项,当选中 others时,我们是可以自定义输入内容并提交到表单的。
开始看到这个问题的时候感觉是很懵的,终于在最后经过我不断的努力下找到大佬解决了这个问题。
在 vue 框架下 我用到的是 element-ui 组件库,因此看到需求,我就想到了 radio 和 checkbox,然后再增加判断是多选还是单选这不就轻轻松松搞定了嘛!于是,我就高高兴兴的想着三下五除二去解决掉这个小case。果不其然,最后还是泪流满面的听大佬讲解。
其实按照上述方法能把页面的展示实现出来,可当时忽略了 v-model 值的影响。 假如,我们从后台接口获取到的值为 data
let question = data;
this.select = [...question];
question.forEach((item) => {
if (item.value.some((i) => i.select_type == "1")) {
this.$set(this.input, [item.后台接收字段值], "");
}
if (item.type === "1") {
// 单选
this.$set(this.ruleForm, [item.后台接收字段值], "");
if (item.mandatory == "1") {
this.$set(this.rules, [item.后台接收字段值], {
required: true,
message: "Required fields cannot be blank!",
trigger: "blur",
});
}
} else if (item.type === "2") {
// 多选
this.$set(this.ruleForm, [item.后台接收字段值], []);
if (item.mandatory == "1") {
this.$set(this.rules, [item.后台接收字段值], {
required: true,
message: "Required fields cannot be blank!",
trigger: "blur",
});
}
}
});
其中 mandatory来判断表单中是否为必填项并提示相关信息。 这样的话就可以解决 v-model 值重复的问题。 v-model 绑定 ruleform[item.后台接收字段值]。
注意,在提交表单的时候:
this.$refs.ruleForm.validate((valid) => {
let params = {};
this.select.forEach((item) => {
if (item.type === "1") {
// 单选
if (
item.value.some(
(i) =>
i.title === this.ruleForm[item.后台接收字段值] &&
i.select_type == "1"
)
) {
params[item.后台接收字段值] =
this.ruleForm[item.后台接收字段值] + " " + this.input[item.后台接收字段值];
} else {
params[item.后台接收字段值] = this.ruleForm[item.后台接收字段值];
}
} else if (item.type === "2") {
// 多选
params[item.后台接收字段值] = [];
this.ruleForm[item.后台接收字段值].forEach((i) => {
let filter = item.value.filter((j) => j.title === i);
if (filter[0].select_type == "1") {
params[item.后台接收字段值].push(i + " " + this.input[item.后台接收字段值]);
} else {
params[item.后台接收字段值].push(i);
}
});
}
});
解决选中 others 时自定义内容提交。
第一次博客,不足之处请指教!
转载自:https://juejin.cn/post/7234324615014809659