el-form---template部分

<el-form :model="form" :rules="rules" ref="adForm">
    <el-form-item label="广告标题:" prop="title">
        <el-input v-model="form.title" placeholder="请输入5~20个字的广告标题"  style="width: 80%;"></el-input>
    </el-form-item>
    <el-form-item label="URL链接:" prop="adUrl">
        <el-input v-model="form.adUrl" placeholder="请输入URL链接"></el-input>
    </el-form-item>
</el-form>
<el-button type="primary" @click="publishHandler">发 布</el-button>

script---data部分

data () {
  // 自定义表单验证
  var checkTitleLength = (rule, value, callback) => {
    if (value.length < 5 || value.length > 20) {
      return callback(new Error('请输入5~20个字的广告标题'))
    }
    // 最后一定要进行callback,否则之后进行 validate 的时候无法进入回调
    callback()
  }
  return {
    form: {
      title: '',
      adUrl: ''
    },
    rules: {
      title: [
        { required: true, message: '广告标题为空', trigger: 'blur' },
        { validator: checkTitleLength, trigger: 'blur' }
      ],
      adUrl: [
        { required: true, message: 'URL链接为空', trigger: 'blur' }
      ]
    }
  }
}

script---method部分

methods: {
    publishHandler () {
      this.$refs.adForm.validate((isPass, noPassList) => {
        // 通过表单验证
        if (isPass) {
          console.log('通过表单验证')
        }
      })
    }
}
02-11 04:13