教你用element-ui實現屬於自己的表單組件

前言

最近因爲新型冠狀病毒,我們都只能呆在家不能出門,所以挺無聊的,就寫下了這篇用element-ui實現一個屬於自己的組件,希望能對大家有幫助!

創建項目

檢查node環境配置

Vue CLI 需要 Node.js 8.9 或更高版本 (推薦 8.11.0+)

node -v

Vue版本

可以使用下列任一命令安裝這個新的包

npm install -g @vue/cli
# OR
yarn global add @vue/cli

查看vue版本

vue --version

創建項目

vue create hello-world

注意:由於我們是開發一個第三方依賴庫,我們選擇 Manually select features

選擇特性安裝到到項目中

 (*) Babel
 ( ) TypeScript
 ( ) Progressive Web App (PWA) Support
 ( ) Router
 ( ) Vuex
 (*) CSS Pre-processors
 (*) Linter / Formatter
 ( ) Unit Testing
 ( ) E2E Testing

安裝哪一種 CSS 預處理語言

(*) Sass/SCSS (with dart-sass)
( ) Sass/SCSS (with node-sass)
( ) Less
( ) Stylus

選擇代碼風格

(*) ESLint with error prevention only
( ) ESLint + Airbnb config
( ) ESLint + Standard config
( ) ESLint + Prettier

哪種方式檢測代碼格式

(*) Lint on save
( ) Lint and fix on commit

是否保存預配置

Save this as a preset for future projects? (y/N)N

最後系統幫我們生成一個完整的項目。

element集成

在項目裏使用

vue add element

首先

需要在element.js裏面導入Form、FormItem和Input

element.js最後的代碼:

import Vue from 'vue'
import { Button,Form,FormItem,Input } from 'element-ui'

Vue.use(Button)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)

組件使用

創建一個登錄表單並可以驗證用戶輸入

  • App.vue
 <div>
        <h3>Element表單</h3>
        <hr>
        <el-form :model="model" :rules="rules" ref="loginForm">
          <el-form-item label="用戶名" prop="username">
            <el-input v-model="model.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="確認密碼" prop="password">
            <el-input type="password" v-model="model.password" autocomplate="off">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('loginForm')">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
      
 data(){
    return{
      value:'',
      model: {username: "ming",password: ""},
      rules: {
        username: [
          {required: true, message: "請輸入用戶名"},
          {min:6,max:10, message: "請輸入6~10的用戶名"},
        ],
        password: [
          {required: true, message: "請輸入密碼"}
        ],
      }
    };
  },
  
   methods: {
    submitForm(form) {
      this.$refs[form].validate(valid=>{
        if(valid){
          alert('請求登錄!')
        }else{
          alert('效驗失敗!')
        }
      })
    }
  }

運行效果:
cmd-markdown-logo
cmd-markdown-logo
cmd-markdown-logo

組件設計

實現Input、Form、FormItem

實現Input

  • App.vue

通過v-model進行雙向數據綁定,這裏的v-model綁定了value值監聽了input事件

<K-input v-model="value"></K-input>

import KInput from './components/input'

export default {
    name: 'app',
    components: {
        KInput
  },
}
  • components/input.vue
<template>
    <div>
        <input :type="type" :value="value" @input="onInput">
    </div>
</template>

<script>
    export default{
        props:{
            value:{
                type:String,
                default: ''
            },
            type:{
                type:String,
                default: 'text'
            }
        },
        methods:{
            onInput(e) {
                let value = e.target.value;
                //input事件觸發設置模型的值並通知父組件
                this.$emit('input',value)
            }
        },
    }
</script>

運行效果
cmd-markdown-logo

實現FormItem

  • App.vue
    <!-- 用戶名 -->
<K-form-Item label="用戶名" prop="username">
  <K-input v-model="model.username"></K-input>
</K-form-Item>
    <!-- 密碼 -->
<K-form-Item label="密碼" prop="password">
  <K-input v-model="model.password" type=""></K-input>
</K-form-Item>

import KInput from './components/input'
import KFormItem from './components/FormItem'

export default {
  name: 'app',
  components: {
    KInput,
    KFormItem
  },
  • components/FormItem.vue
<template>
    <div>
        <label for="">{{label}}</label>
        <div>
            <slot></slot>
            <p v-if="errStatus">{{errMessage}}</p>
        </div>
    </div>
</template>
<script>
    import Schema from 'async-validator'
    export default{
        inject: ['KForm'],
        props:['label','prop'],
        data(){
            return{
                errMessage: '',
                errStatus: false
            }
        },
        mounted(){
            this.$on('validate',this.validator)
        },
        methods:{
            validator(){
                //有兩個Input,一個用戶名,一個密碼
                const rules = this.KForm.rules[this.prop];
                const value = this.KForm.model[this.prop];

                const descriptor = {[this.prop]:rules};
                const schema = new Schema({descriptor});
                schema.validate({[this.prop]:value},errors =>{
                    if(errors){
                        this.errMessage = errors[0].message;
                        this.errStatus = true;
                    }else{
                        this.errMessage = '';
                        this.errStatus = '';
                    }
                })
            }
        }
    }
</script>

運行結果
cmd-markdown-logo
cmd-markdown-logo

實現Form

  • App.vue
<K-form :model="model" :rules="rules">
<!-- 用戶名 -->
<K-form-Item label="用戶名" prop="username">
  <K-input v-model="model.username"></K-input>
</K-form-Item>
<!-- 密碼 -->
<K-form-Item label="密碼" prop="password">
  <K-input v-model="model.password" type=""></K-input>
</K-form-Item>
</K-form>

import KInput from './components/input'
import KFormItem from './components/FormItem'
import KForm from './components/Form'
export default {
  name: 'app',
  components: {
    KInput,
    KFormItem,
    KForm
  },
  • components/Form.vue
<template>
    <div>
        <form>
            <slot>

            </slot>
        </form>
    </div>
</template>
<script>
    export default{
        provide(){
            return {
                KForm: this
            }
        },
        props:{
            model:{
                type: Object,
                required: true
            },
            rules:{
                type: Object
            }
        }
    }
</script>

運行效果
cmd-markdown-logo

代碼地址

https://github.com/shifengming/element-form

最後

如果本文對你有幫助得話,給本文點個贊❤️❤️❤️

歡迎大家加入,一起學習前端,共同進步!
cmd-markdown-logo
cmd-markdown-logo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章