做项目时遇到一个功能:对每个商品进行评价和必填项校验。
原型如如下:
最后实现方式是:
- 循环每一个el-form-item,
- 在el-form-item标签上加rules校验规则,
- props根据索引动态绑定
相关代码如下:
<el-form :model="goodsRateObj" ref="goodsRateObj" inline>
<div class="goods_item" v-for="(item,index) in goodsRateObj.tags" :key="item.skuId">
<div class="goods">
<img :src="item.goodsCover" >
<span>{{ item.goodsName }}</span>
</div>
<el-form-item label="商品质量:" :prop="`tags[${index}].commodityScore`" :rules='rules1'>
<el-rate v-model="item.commodityScore"></el-rate>
</el-form-item>
<el-form-item label="物流速度:" :prop="`tags[${index}].expressScore`" :rules="rules2">
<el-rate v-model="item.expressScore"></el-rate>
</el-form-item>
<el-form-item label="服务态度:" :prop="`tags[${index}].serviceAttitude`" :rules="rules3">
<el-rate v-model="item.serviceAttitude"></el-rate>
</el-form-item>
<el-form-item label="评价内容:" :prop="`tags[${index}].comment`" :rules="rules4">
<el-input type="textarea" v-model="item.comment" maxlength="200" show-word-limit :autosize="{'minRows': 4}"></el-input>
</el-form-item>
</div>
</el-form>
export default {
data() {
var validateZero = (rule, value, callback) => {
if (value === 0) {
callback(new Error('评分最低一颗星'))
} else {
callback()
}
}
return {
goodsRateObj: { tags: [{ commodityScore: '', expressScore: '', serviceAttitude: '', comment: '' }] },
rules1: [
{ required: true, message: '请输入商品质量', trigger: 'change' },
{ validator: validateZero, trigger: 'change' }
],
rules2: [
{ required: true, message: '请选择物流速度', trigger: 'change' },
{ validator: validateZero, trigger: 'change' }
],
rules3: [
{ required: true, message: '请选择服务态度', trigger: 'change' },
{ validator: validateZero, trigger: 'change' }
],
rules4: [{ required: true, message: '请输入评价内容', trigger: 'blur' }]
}
},
mounted() {},
methods: {
submitFn() {
this.$refs.goodsRateObj.validate((valid) => {
if (valid) {
console.log('提交')
} else {
return false
}
})
}
}
}