相信不少人都有過這樣的代碼ui
{ name: [ { required: true, message: '請輸入活動名稱', trigger: 'blur' }, ], region: [ { required: true, message: '請選擇活動區域', trigger: 'change' } ], }
額滴惡瓜腦膜炎上帝啊, 這是要坐實我搬磚皇帝的身份麼,一個required要我寫這麼多代碼? 我就一個必填, 你默認給我整個英文,仍是this
name is required
唉, 不得不想出點腦瓜仁方便方便了。
二話不說,
我包裝了下el-form, 看下:prototype
<template> <el-form ref="form" v-bind="$attrs" :rules="defaultRules" size="small"> <slot></slot> </el-form> </template> <script> import validator from "./validator"; /** * Basic Form Components */ export default { inheritAttrs: false, data() { return { defaultRules: {}, // Default configuration made by interception validateList: [], }; }, created() { // 讀取規則列表 this.readRuleList(); const arr = this.$slots.default.map(v => ({ ...v.componentOptions.propsData, ...v.data.attrs })); arr.forEach(v => { if (Object.prototype.hasOwnProperty.call(v, "required")) { if (!this.defaultRules[v.prop]) { this.$set(this.defaultRules, v.prop, []); } this.defaultRules[v.prop].push({ required: true, message: `${v.label}不能爲空`, // 重點這句 trigger: "blur" }); } this.validateList.forEach(val => { if (Object.prototype.hasOwnProperty.call(v, val)) { if (!this.defaultRules[v.prop]) { this.$set(this.defaultRules, v.prop, []); } this.defaultRules[v.prop].push({ validator: validator[val](this), trigger: "blur" }); } }); }); }, methods: { validate(fn) { return this.$refs.form.validate(fn); }, reset() { this.$refs.form.resetFields(); }, readRuleList() { this.validateList = Object.keys(require("./validator/index").default); } } }; </script>
這麼用:code
<base-form> <el-form-item prop="title" label="標題" required> <el-input v-model="addForm.title"></el-input> </el-form-item> </base-form>
就只要在form-item上寫個 required! message默認就是標題不能爲空
固然這個base-form還能夠隨便加定好的屬性,你看:component
validator.js
/** * Verifier */ export default { mobile: () => (rule, value, callback) => { if (!/^1[0-9]{10}$/.test(value)) { callback(new Error("手機號碼錯誤")); } else { callback(); } }, email: () => (rule, value, callback) => { if (!/[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) { callback(new Error("電子郵箱格式錯誤")); } else { callback(); } } };
你只要這麼使用:orm
<base-form> <el-form-item prop="title" label="標題" email> <el-input v-model="addForm.title"></el-input> </el-form-item> </base-form>
郵箱驗證就加上去啦!ip
噹噹固然,闊以疊加input
<base-form> <el-form-item prop="title" label="標題" email required> <el-input v-model="addForm.title"></el-input> </el-form-item> </base-form>
ohohohohohohohoh!! it
噹噹噹噹噹固然, base-form是不會沖掉本來el-form的屬性的, 這麼炫炫的組件不copy試試嗎?io