赞
踩
先看需求:(不想看的直接拉到最后)
【需求说明】
6、如状态为上架时,库存为必填,下架状态时,库存为可填,前面无星号
实现方法:使用this.$set()和this.$delete()
上代码:
由于设计商业隐私,代码只上传一部分:
- <el-form :model="commodityForm" ref="commodityForm" :rules="rules" label-width="120px">
-
- 其他字段......
-
- <el-form-item label="上下架状态" prop="status">
- <el-switch
- v-model="commodityForm.status"
- :active-value="1"
- :inactive-value="0"
- @change="switchChange"
- >
- </el-switch>
- </el-form-item>
- </el-form>
表单data中原来的rules:
- // 表单校验
- rules:{
- name: [{ required: true, message: "请输入商品名称", trigger: ['blur','change']}],
- title: [{ required: true, message: "请输入商品标题", trigger: ['blur','change']}],
- commodityFormImg:[{ required: true, message: '请上传商品图片', trigger: 'change'}],
- typeId: [{ required: true, message: '请选择所属分类', trigger: 'change'}],
- brandId: [{ required: true, message: '请选择商品品牌', trigger: 'change'}],
- specification: [{ required: true, message: '请选择商品规格', trigger: ['blur','change']}],
- sellingPrice: [{ required: true, message: '请输入销售价', trigger: ['blur','change']}],
- // stock: [{ required: true, message: '请输入库存', trigger: ['blur','change']}],
- detail: [
- { required: true, message: "商品详情不能为空", trigger: "blur" },
- { validator: validateEditor, trigger: 'blur,change' }
- ]
- },
不添加上下架状态的rules
在change事件中进行判断:重点方法在这里!!!!!!!!!!
- // 上下架开关事件
- switchChange(e) {
- if(e != 1) {
- //删除校验的关键的两行代码(两行都要!!!!!!!!!!!!!!!)
- // 这个只能删除文字提示,但是星号还在,
- this.$refs["commodityForm"].clearValidate(["stock"]);
- // 这个只能删除星号提示,但是文字还在
- this.$delete(this.rules,'stock');
- }else{
- //添加校验代码(!!!!!!!!!!!!!!!)
- this.$set(this.rules,'stock',[{ required: true, message: '请输入库存', trigger:
- ['blur','change']}])
- }
- }
动态添加删除rules
2023-1-29二更一个最新的方法:
- <el-form-item label="库存" prop="stock" :rules="commodityForm.status == 1 ? { required: true, message: '请输入库存', trigger: ['blur','change']} : {}">
- <el-input v-model.trim="commodityForm.stock" @input="commodityForm.stock = commodityForm.stock.replace(/[^\d]/g, '')" size="small" placeholder="请输入库存"></el-input>
- </el-form-item>
感谢我的好同事教我做事哈哈哈
:rules="commodityForm.status == 1 ? { required: true, message: '请输入库存', trigger: ['blur','change']} : {}"
同时方法中的代码留一个:
- switchChange(e) {
- if(e != 1) {
- this.$refs["commodityForm"].clearValidate(["stock"]);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。