vue實(shí)現(xiàn)類似element中表單的封裝

前段時(shí)間寫過一篇react對(duì)input表單驗(yàn)證的封裝,實(shí)現(xiàn)的效果與ant design類似。
今天來模仿element ui實(shí)現(xiàn)vue中對(duì)表單驗(yàn)證的封裝。
基于vue cli 創(chuàng)建一個(gè)簡單地項(xiàng)目即可,element ui中使用的async-validator框架對(duì)表單進(jìn)行的驗(yàn)證,我們同樣使用這個(gè)框架。首先安裝一下

npm install async-validator

啟動(dòng)項(xiàng)目,我在src的components下分別創(chuàng)建三個(gè)vue文件,分別用于創(chuàng)建form,form-item和input。
對(duì)于單個(gè)表單的驗(yàn)證放到form-item中進(jìn)行,input中實(shí)現(xiàn)value的傳遞并且通知form-item進(jìn)行驗(yàn)證。我在form實(shí)現(xiàn)一個(gè)對(duì)整個(gè)表單驗(yàn)證的方法,提交表單時(shí)使用,并且form中接收表單值和校驗(yàn)規(guī)則。下面代碼實(shí)現(xiàn):

src/components/exinput.vue(創(chuàng)建input組件)

<template>
    <input :type="type" :value="value" @input="handleInput"  />
</template>
<script>
export default {
    props:{
        value: {
            type: String,
            default: ""
        },
        type: {
            type: String,
            default: "text"
        }
    },
    methods: {
        handleInput(e){ 
            this.$emit("input", e.target.value);//input在這是寫死的,這樣父組件可直接@input
            this.$parent.$emit("validate");//當(dāng)值改變時(shí),通知父組件校驗(yàn)
        }
    }
}
</script>

src/components/exformitem.vue(創(chuàng)建form-item組件)

<template>
    <div>
        <label v-if="label">{{label}}</label>
        <slot></slot>//slot占位,一會(huì)放入input組件
        <p v-if="error" style="color:red">{{error}}</p>
    </div>
</template>
<script>
import Schema from "async-validator"
export default {
    inject:["form"],//接收form組件傳遞過來值
    props: {
        label: {
            type: String,
            default: ""
        },
        prop: { //用戶取的單個(gè)表單名,比如:uname,password等,與model和rules中的鍵一致。
            type: String
        }
    },
    data(){
        return {
            error: ""http://存放驗(yàn)證失敗時(shí)的信息
        }
    },
    mounted(){
        this.$on("validate",this.validate)
    },
    methods:{
        validate(){
            //使用async-validator驗(yàn)證時(shí),校驗(yàn)規(guī)則和校驗(yàn)的值以鍵值對(duì)方式傳入
            const val = this.form.model[this.prop];//獲取當(dāng)前校驗(yàn)的input值
            const rule = this.form.rules[this.prop];//獲取當(dāng)前input的校驗(yàn)規(guī)則
            const descriptor = {[this.prop]:rule};
            const schema = new Schema(descriptor);
            const source = {[this.prop]: val};
            schema.validate(source, error=>{
                if(error) {
                    this.error = error[0].message;//如果有錯(cuò)誤,將錯(cuò)誤信息賦給error
                    this.form.rules[this.prop].error = true;//如果有錯(cuò)誤我給當(dāng)前的校驗(yàn)規(guī)則中添加一個(gè)error屬性賦值為true,主要是方便提交時(shí)校驗(yàn)
                }else{
                    this.error = "";
                    this.form.rules[this.prop].error = false;
                }
            })
        }
    }
}
</script>

src/components/exinput.vue(創(chuàng)建form組件)

<template>
    <form>
        <slot></slot>//一會(huì)放入form-item組件
    </form>
</template>
<script>
export default {
    provide(){//寫法上和data一樣,組件傳值
        return {
            form: this
        }
    },
    props: {
        model: {
            type: Object
        },
        rules: {
            type: Object
        }
    },
    methods:{
        validate(cb){//表單提交時(shí)調(diào)用的方法,傳入一個(gè)回調(diào)函數(shù)
            var ispass = Object.keys(this.model).every(item => {
                return this.model[item] && !this.rules.error
            })
            cb(ispass);//將校驗(yàn)結(jié)果傳遞出去
        }
    }
}
</script>

上面的組件中用到了provide/inject,這兩個(gè)是成對(duì)出現(xiàn)的provide用于向下傳值,inject用于接收值。可隔代傳值。與react中的上下文有點(diǎn)類似。
接下來我們刪除App.vue中的內(nèi)容,將我們創(chuàng)建好的三個(gè)組件導(dǎo)入進(jìn)去

App.vue

<template>
  <div id="app">
      <ex-form :rules="rulesform" :model="modelform" ref="loginForm">
        <ex-form-item label="用戶名" prop="uname">
          <ex-input v-model="modelform.uname"></ex-input>
        </ex-form-item>
        <ex-form-item label="密碼" prop="password">
          <ex-input type="password" v-model="modelform.password"></ex-input>
        </ex-form-item>
        <ex-form-item>
          <button type="button"  @click="submitForm('loginForm')" >提交</button>
        </ex-form-item>
       </ex-form>
  </div>
</template>

<script>
import ExInput from './components/exinput'
import ExFormItem from './components/exformitem'
import ExForm from './components/exform'

export default {
  components: {
    ExInput,
    ExFormItem,
    ExForm
  },
  data(){
    return {
      modelform:{
        uname:"",
        password:""
      },
      rulesform:{
        uname:[{required: true, message: "用戶名不能為空"}],
        password:[{required: true, message: "密碼不能為空"}]
      }
    }
  },
  methods:{
    submitForm(form){
      this.$refs[form].validate(vate => {
        if(vate){
          console.log("提交成功")
        }else{
          console.log("提交失敗")
        }
      });
    }
  }
}
</script>

prop中傳遞的值是modelform和rulesform的鍵,所以在exformitem.vue文件中才能通過this.form.model[this.prop]/this.form.rules[this.prop]獲取到對(duì)應(yīng)的值。
查看頁面


1.gif
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容