<template>
<view class="u-page">
<!-- 注意,如果需要兼容微信小程序,最好通过setRules方法设置rules规则 -->
<u--form labelPosition="top" labelWidth=450 :model="model1" :rules="rules" ref="form1">
<u-form-item v-for="(item,index) in model1.qList" :label="item.subjectContent" :key="index"
:prop="'qList.'+index+'.state'" borderBottom :ref="'item'+item.id">
<u-radio-group v-if="item.type=='单选'" v-model="item.state" placement="column"
@change="(e) => onChangeMarkChoose(e,item)">
<u-radio :customStyle="{marginRight: '16px'}" v-for="(items, indexs) in item.optionList"
:key="indexs" :label="items.optionContent" :name="indexs+1" @change="radioChange">
</u-radio>
</u-radio-group>
</u-form-item>
</u--form>
<u-button type="primary" text="提交" customStyle="margin-top: 20px" @click="submit"></u-button>
</view>
</template>
<script>
export default {
data() {
return {
model1: {
qList: [],
},
rules: {},
}
},
onReady() {
// 如果需要兼容微信小程序,并且校验规则中含有方法等,只能通过setRules方法设置规则
this.$refs.form1.setRules(this.rules)
},
methods: {
getQuestionList() {
// 问卷数据格式
var data = [{
"id": '1',
"subjectContent": '问题一',
"type": '单选',
"state": '',
"optionList": [{
"id": '1',
"optionContent": "选项1",
},
{
"id": '2',
"optionContent": "选项2",
},
{
"id": '3',
"optionContent": "选项3",
},
]
}, ]
this.model1.qList = data
},
groupChange(n) {
console.log('groupChange', n);
},
radioChange(n) {
console.log('radioChange', n);
},
onChangeMarkChoose(e, item) {},
navigateBack() {
uni.navigateBack()
},
change(e) {},
submit() {
// 如果有错误,会在catch中返回报错信息数组,校验通过则在then中返回true
this.$refs.form1.validate().then(res => {
uni.$u.toast('校验通过')
}).catch(errors => {
uni.$u.toast('有内容没有填写完整')
})
},
reset() {
const validateList = []
this.$refs.form1.resetFields()
this.$refs.form1.clearValidate()
setTimeout(() => {
this.$refs.form1.clearValidate(validateList)
// 或者使用 this.$refs.form1.clearValidate()
}, 10)
},
hideKeyboard() {
uni.hideKeyboard()
}
},
created() {
this.getQuestionList()
//循环问题数组
this.model1.qList.forEach((item, index) => {
if (item.type == '单选') { //单选,type: number
this.rules['qList.' + index + '.state'] = {
type: 'number',
required: true,
message: '请选择一项,不能为空',
trigger: ['change']
}
}
})
},
onLoad() {
},
}
</script>
<style lang="scss">
</style>
微信小程序的setRules方式在H5环境是不需要的,问题可能出在这个地方。
uView中的动态Rules在小程序中加载可能有时间的先后顺序,即在Rules未完全动态生成时,就已经被使用?
因为UniAPP生成的微信小程序代码很复杂,没有跟踪到出错位置。
希望能了解为什么在微信小程序中出错,找出在微信小程序中可以动态完成 uView 中 从数组中动态加载 u-form-item的方法。
if (item.type == '单选') { //单选,type: number
//this.rules['qList.' + index + '.state'] = {
//=======>改索引的形式试试
this.rules['qList[' + index + '].state'] = {
type: 'number',
required: true,
message: '请选择一项,不能为空',
trigger: ['change']
}
}