<template>
<view>
<view>
<uni-forms ref="dynamicForm" :rules="dynamicRules" :modelValue="dynamicFormData">
<uni-forms-item label-position="top" label-width="375" v-for="(item, index) in dynamicLists"
:key="item.id" :label="index + 1 + '.' + item.label" required :rules="item.rules"
:name="'domains[' + item.id + ']'">
<uni-easyinput class="easyinput" trim="all" :autoHeight="true" maxlength="500" type="textarea"
v-model="item.value" placeholder="请输入内容" />
</uni-forms-item>
</uni-forms>
</view>
<view class="subbtn">
<button class="box_null_footer_btn" @click="submit">
去上传
</button>
</view>
</view>
</template>
<script>
data() {
return {
detail: {},//后端返回数据
// 自定义表单校验规则
dynamicRules: {
// 这里随便写一个,不然会报错
name: {
rules: [{
required: true,
errorMessage: '姓名不能为空'
}]
},
},
dynamicFormData: {},
dynamicLists: []
}
},
onLoad(e) {
this.getForm()
},
// 必须要在onReady生命周期,因为onLoad生命周期组件可能尚未创建完毕
onReady() {
this.$refs.dynamicForm.setRules(this.dynamicRules)
},
methods: {
// 获取表单
async getForm() {
const res = await getCaseForm()
console.log(res, "表单");
if (res.status == 0) {
this.detail = res.data
for (var i = 0; i < this.detail.questions.length; i++) {
this.dynamicLists.push({
label: this.detail.questions[i].problem,
value: "",
rules: [{
'required': true,
errorMessage: "请输入" + this.detail.questions[i].problem
}],
id: this.detail.questions[i].id
})
}
console.log(this.dynamicLists, "处理数据");
} else {
this.$u.toast(res.msg)
}
},
async submit() {
console.log(this.form, "提交数据");
this.$refs.dynamicForm.validate(valid => {
if (!valid) {
console.log('验证通过', this.dynamicLists);
// const res = await subCaseForm()
// console.log(res, '表单提交');
} else {
console.log('验证失败', this.dynamicLists);
}
});
},
}
</script>
<style lang="scss" scoped>
.subbtn {
margin-top: 40rpx;
padding-bottom: 40rpx;
.box_null_footer_btn {
width: 100%;
height: 100rpx;
background: linear-gradient(125deg, #EFD8BD 0%, #E2C3A3 100%);
box-shadow: 0px 4px 10px 0px #E5E5E5;
border-radius: 50rpx;
display: flex;
justify-content: center;
align-items: center;
font-size: 32rpx;
font-family: PingFang SC-Regular, PingFang SC;
font-weight: 400;
color: #794F35;
}
}
</style>
uniapp根据后端返回,生成动态表单
于 2022-11-21 14:21:36 首次发布