Vue Elementui implements instance code for search bar public components package

VUE background management system, there will be a lot of table pages, there will be some search options above, and the table is directly using EL-TABLE, and the search bar area Every time you write, it is very cumbersome, and the style written by each person is different in many people development. The layout style cannot be unified.

Therefore, consider making a package, unified configuration reference, and enhance development and maintenance efficiency and interface unity.

vue elementui 实现搜索栏公共组件封装的实例代码

2, analysis

is used in ELEMENTUI Framework, search bar This form is submitted, first to use the EL-Form component to encapsulate, and complex points are the form items may have many kinds, such as the input box, SELECT selection box, datetime selection box, date time range selection box, Cascader Cascade Selection Box, etc., each field name Prop, name Label, binding properties method is not the same. Therefore, it cannot be processed by ordinary binding individual properties, and the way the SLOT slot cannot be simplified, and finally decides to parse the generated corresponding structure by passing a configuration item array.

3, implementation

The current implementation is composed of two parts, part of the FORM form assembly, accepting the array of configuration items passed by the parent component, part of the package is some common The form of the form is controlled by V-IF. The form is introduced into the form component, loop traversal, and matches the display specific form item according to the passing form type.

SEARCHMM.VUE example code:

      FormiteM Table Single Component Code:   

      4, key points    Since the ElementUI form parties themselves have a lot of configuration properties, it is impossible to write all the properties and methods, and want to be seamlessly supported, you need to use V-bind for Vue. And V-ON features, Vue's V-BIND and V-ON support assignments are object types, and VUE will automatically use the properties in the object to be binded in turn, V2.4.0 + support. 
5, parameter configuration item explanation

(1) Example:

[{Label : ‘User name’, // Label text prop: ‘username’, // field name Element: ‘EL-INPUT’, // Specify ElementUI Components InitValue: ‘Ahuang’, // Field Initial Value PlaceHolder: ‘Please enter User name ‘, // ElementUI component property rules: [{required: true, message:’ required “, trigger: ‘blur’}], // ELEMENTUI Component property Events: {// ElementUI component method INPUT (VAL) {Console.log (VAL)},}}]

Label is used to bind to Label on EL-FORM-ITEM, form item title

Prop The PROP, FORM name, must -fect

element name, required
ELEMENT specifies the component name of the ElementUI form, the initial value of the INITVALUE form, canElect

Events object, object plug method, JS native method, or Elementui form single component support can be added, through V-ON traversal
… other ElementUI table single component supported attribute or HTML native properties All can be added, for example, for example, a Rules form check, PlaceHolder prompt, through V-BIND traversal
 (2) Parameter passed the parsing process:   First, in the SearchForm.Vue component Receive parameters by PROPS: 

{Type: Array, Required: true, default () {return []}},

 // Add initial value addinitvalue () {const Obj = {} this.formoptions.Foreach (v => {if (v.initvalue! == undefined) {Obj [v.prop] = v.initvalue}} "this.formData = obj}   
One part of the configuration item is bound to the EL-FORM-ITEM, part is passed to the formitem form single component and then bind:

FormItem.Vue form single component PrOPS accepts passage:

ItemOptions: {type: Object, default () {return {}}}
   The received parameter itemOptions is processed in computed. Generate all attribute objects to be bound to bindprops:    
// Binding attribute BINDPROPS () {let Obj = {… this.ItemOptions } // Remove the useful or irrelevant redundant attribute delete obj.label delete obj.prop delete obj.Element delete obj.initvalue delete obj.rules delete obj.Events if (obj.element === ‘EL- Select ‘) {Delete Obj.Options} Return Obj},

All method objects to be bound to bindevents:

// Binding Method Bindevents () {Return this.itemoptions.Events || {}},
Last DOM Use these data bindings:

 (3 ) Treatment for special circumstances   Because ELEMENTUI's EL-SELECT is through EL-Option traversal implementation, and traversal array Options Press Elementui official to be binding on EL-SELECT, so adding an Options in the EL-SELECT configuration item, the data number of the SELECT selection. 

  Elementui The date time selector is divided into many kinds. According to the business needs, I will be divided into three separate processing according to Type, the most commonly used the DateTimerange Date Time Rangerator, as the default, there is a MonthRange, the rest Both are one. (Specifically, see the complete code at the end of the article)  
6, button group

The button is actually then then several, there is no need to do too much package, according to the business Which buttons will be encapsulated, and I have installed three buttons here.

Accept a string identification button group via PROPS:

/ / Submit button item, multiple comma separation (Query search, export, reset reset) Btnitems: {TYPE: STRING, DEFAULT () {Return ‘Search’}}

  7, mode of use    

VUE Data:
  Formoptions: [{label: 'Submissions',Prop: 'Content', Element: 'El-Input', {Label: 'Type', Prop: 'Type', Element: 'El-select', Options: [{Label: 'gives some opinions', Value: '1'}, {Label: 'After-sales issue', value: '2'}]}, {label: 'status', prop: 'status', element: 'el-select', options: getFeedbackStatus ()}, {Label: 'Submit Time', Prop: 'TimeRange', Element: 'El-Date-Picker'}],      Vue Methods : 

// Gets the data of the search form submitted inSearch (VAL) {Console.log (VAL)}

8, complete code

(1) Searchform.Vue
/ ** * Created by hanxueqiang on 200107 * * Search column public component * /


Import formItem from ‘./formitem’Import tools from’ @ / utils / tools’Export default {prons: {/ ** * Form configuration * Example: * [{* label: ‘User name, // Label text * Prop: ‘username’, // field name * Element: ‘el-input’, // Specify ElementUI components * initValue: ‘Ahuang’, // field initial value * PlaceHolder: ‘Please enter your username’, // ElementUI Component Properties * Rules: [{Required: True, Message: ‘Required “, Trigger:’ BLUR ‘}], // ElementUI Component Attribute * Events: {// ElementUI Component System * Input (VAL) {* Console .log (val) *}, * … // Additional ElementUI components support method *} * … // can add attributes supported by any ELEMENTUI component *}] * / flmoptions : {TYPE: ARRAY, Required: true, default () {return []}}, // Submit button item, multiple comma separation (Query, Export, Reset) btnitems: {type: string, default () {return ‘search’}}}}, data () {return {formdata: {}}},Computed: {newkeys () {return (v => {return tools.createuniquestring ()}}}, created () {this.addinitvalue ()}}: {// Check ONVALIDATE (CALLBACK) ) {this. $ refs.formref.validate (Valid => {if (valid) {console.log (‘submission success’) console.log (this.formData) callback ()}})}, // Search ONSearch ) {this.onvalidate (() => {this. $ EMIT (‘OnSearch’, this.formData)}}, // Export Onexport () {this.onvalidate (() => {this. $ EMIT (‘ Onexport ‘, this.formData)}}}}}}}}}} ()}}} ()} ()} ()} $ refs.formref.resetfields ()}, // Add initial value addinitvalue () {const object = {} this.formtions.Foreach (v => {IF (v.initvalue! == undefined) {OBJ [v.prop] = v.initvalue}}) this.formData = Obj}}}}}}
.Search-form-box {display: flex; margin-bottom: 15px ;. .btn-box {padding-top: 5px; display: flex; button {height: 28px;}} .el-form}}} .el-form {/ deEP / .el-form-item__label {padding-right: 0;} .el-form-item {margin-bottom: 0; & .is-error {margin-bottom: 22px;}} // EL-INPUT width / deEP / .form-item {> .el-input: not (.el-date-editor) {width: 120px;}} / deep / .el-select {width: 120px;} / deep / .el-cascader {width: 200px;}}}

(2) Formitem.Vue

/ ** * Created by hanxueqiang on 200107 * * Table Single Match * /


Import Tools from ‘@ /utils / tools’export default {inheritAttrs: false, props: {value: {}, itemOptions: {type: Object, default () {return {}}}}, data () {return {pickerOptionsRange: tools.pickerOptionsRange, pickerOptionsRangeMonth : Tools.PickerOptionsRangemonth}}, computed: {// bidirectional binding data value CURRENTVAL: {Get () {Return this.Value}, set (val) {this. $ EMIT (‘Input’, VAL)}}, / / Binding Properties Bindprops () {let Obj = {… this.itemoptions} // Remove redundant attribute delete obj.label delete obj.prop delete obj.Elete Obj.Rules Delete Obj.Events IF (obj.element) {delete obj.Options} returnobj}, // Binding method Bindevents () {return || {}}, // EL-INPUT IsInput () {Return this.ItemOptions.Element === ‘EL-INPUT’}, // EL-INPUT-Number isinputNumber () {Return this.ItemOptions.Element === ‘el-infut-number’}, // EL-select isselect () {Return THISTEMOPTIONS.ELEMENT === ‘El-select’}, // el-date-picker (type: datetimerange / daterege) isdatePickerDateRange () {const isdatepicker = this.ItemOptions.Element === ‘el-date-picker ‘const isdaterange =! this.itemoptions.type || this.itemoptions.type ===’ datetimerange ‘|| this.itemoptions.type ===’ dateRange ‘return isdatePicker && isdateRange}, // el-date-picker type: monthrange) isDatePickerMonthRange () {const isDatePicker = this.itemOptions.element === ‘el-date-picker’ const isMonthRange = this.itemOptions.type === ‘monthrange’ return isDatePicker && isMonthRange}, // el- Date-Picker (Type:other) isDatePickerOthers () {const isDatePicker = this.itemOptions.element === ‘el-date-picker’ return isDatePicker &&! this.isDatePickerDateRange &&! this.isDatePickerMonthRange}, // el-cascader isCascader () {return this. ItemOptions.Element === ‘el-cascader’}}, created () {}, methods: {}, components: {}}

(3) Some of the modified function methods Tools.js
  / ** * Create a unique string * @return { string} ojgdvbvaua40 * / function createUniqueString () {const timestamp = + new Date () + '' const randomNum = parseInt ((1 + Math.random ()) * 65536) + '' return (+ (randomNum + timestamp)) .tostring (32)} // Elementui Date Time Range Express Option Const PickerOptionsRange = {Shortcuts: [{Text: 'Today', OnClick (Picker) {const end = newDate () const start = new date (new date (). Todatestring ()) Start.SetTime (Start.getTime ()) Picker. $ EMIT ('Pick', [Start, End])}}, {text: ' Recent week ', onclick (picker) {const end = new date () const start = new date () start.settime (end.gettime () - 3600 * 1000 * 24 * 7) Picker. $ EMIT (' Pick ', [start, end])}}, {text: 'The last month', onclick (picker) {const end = new date () const start = new date () start. settime () - 3600 * 1000 * 24 * 30) Picker. $ EMIT ('pick', [start, end])}}, {text: 'The last three months', onclick (picker) {const end = new date () const start = new Date () Start.SetTime (Start.getTime () - 3600 * 1000 * 24 * 90) Picker. $ EMIT ('Pick', [Start, End])}}]} // Elementui Moon Range Express Option Const PickerOptionsRangeMonth = { Shortcuts: [{text: 'This year's current', onclick (picker) {const end = new date () const start = new date (new date (). GetFullyear (), 0) Picker. $ EMIT ('pick', [start, end]) }}, {text: 'The last half year', onclick (picker) {const end = new date () const start = new date () start.getmonth (Start.getMonth () - 6) Picker. $ EMIT ('Pick' , [start, end])}}, {text: 'The last year', onclick (picker) {const end = new date () const start = new date () start.setMonth (Start.getMonth () - 12) Picker. $ EMIT ('Pick', [Start, End])}}]  
(4) Some ElmentUI global styles of modification // EL-INPUT-NUMBER (Controls-Position = "Right"). EL-INPUT-NUMBER.IS-Controls-Right {.el-Input-Number__Decrease { Display: none;} .el-input-number__increase {display: none; TOP: 2PX; / / FIX STyle bug} &: hover {.el-input-number__decrease {display: inline-block;} .el-input-number__increase {display: inline-block;}} .el-input__inner {text-align: left; padding-left : 5px; Padding-right: 40px;}} // el-date-picker datetimerange.el-datetimerange {.el-range-separator {width: 24px; color: # 999 Padding: 0;} .el-range__icon {margin-left: 0;} & .el-infut__inner {vertical-align: middle; padding: 3px 5px;} & .el-range-editor - medium {width: 380px ; .el-range-separator {line-height: 30px;}} & .el-range-editor - mini {width: 330px; .el-range-separator {line-height: 22px;}}} // el -date-picker not datetimerange.el-date-editor {.el-input_prefix {left: 0; Top: 1px;} .el-input__suffix {right:0; top: 1px;} .el-input__inner {padding: 0 25px;} & .el-input - mini {width: 175px;} & .el-input - medium {width: 195px;}} // Input Padding.el-infut__inner {padding: 0 5px;}
Summary The above is a small series to introduce Vue Elementui implements the search bar public component package, I hope to help everyone. If you have any questions, please leave a message, Xiaobian will reply to everyone in time. Thank you very much for your support of Tumi Cloud Website!
If you think this article is helpful, welcome to reprint, please indicate the source, thank you!
© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment