Use iView to dynamically create form forms
Form generator with data collection, verification and submission functions, including check box, single box, input box, drop-down selection box and other elements, provincial and urban three-level linkage, time selection, date selection, color selection, file/picture upload functions.
Version 1.1 Major updates
- Internal restructuring
- New provincial and urban three-level linkage components
- Added component event extension
- Optimize file upload, time selection and other components
To be perfect
- Dynamically display hidden forms
- Dynamically add forms
- Tree control generation
The sample
The installation
npm install form-createCopy the code
OR
git clone https://github.com/xaboy/form-create.git
cd form-create
npm installCopy the code
The introduction of
<! -- import Vue --> <script src="node_modules/vue/dist/vue.min.js"></script> <! -- import iview --> <link rel="stylesheet" href="node_modules/iview/dist/styles/iview.css"> <script src="node_modules/iview/dist/iview.min.js"></script> <! <script SRC ="/district/province_city_area.js"></script> <! <script SRC ="mock. Js "></script> <! -- import formCreate --> <script src="dist/form-create.min.js"></script>Copy the code
** Ensure that the iView version is >=2.9.2; otherwise, problems may occur
use
let rules = window.mock; new Vue({ mounted:function(){ var $f = this.$formCreate(rules,{ onSubmit:function (formData) { console.log(formData); $f.submitStatus({loading:true}); }}); }})Copy the code
$formCreate parameters
Rules form rules [inputRule,selectRule…]
Options component configuration (see createOptions at bottom for details)
$f instance method
Get form data
$f.formData()
Gets the specified field data
$f.getValue(field)
Modifying form data
$f.changeField(field,value)
Form validation
$f.validate(successFn,errorFn)
The form validates the specified field
$f.validateField(field,errorFn)
Reset the form
$f.resetFields()
Delete the entire form
$f.remove()
Delete a specified field
$f.removeField(field)
Get all fields of the form
$f.fields()
Submit the form
$f.submit()
Change the status of the submit button
$f.submitStatus(props) // See createOptions.submitbtn at the bottom
Rules rules
Hidden Hidden field
HiddenRule: {type:"hidden", field:"id", // field name value:"14" //input value}Copy the code
The input fields
InputRule: {type:"input", title:" merchandise name",// label name field:"goods_name",// value:" iPhone 7",//input value, props: {"type": "text", // Input field type, the options are text, password, textarea, URL, email, date "clearable":false, // Whether to display the empty button "disabled": "Readonly ": false, "rows": 4, "autosize": {minRows: 2, maxRows: 6} "number": {minRows: 2, maxRows: 6} "number": False, // Convert user input to Number type "autofocus": false, // automatically get focus" autocomplete": "Off ", // native autocomplete (off and ON "placeholder") :" Please input the commodity name ", // placeholder text "size": "Default ", // Enter the size of the box. The options are large, small, default, or no value. "spellcheck": False, // The native spellCheck properties "required":true,}, event:{// Enter (event)=>{}, // After setting the icon property, Triggered when clicking on the icon click: (event) = > {}, / / data changes trigger change: (event) = > {}, / / input box focus triggered when focus: (event) = > {}, / / input box loses focus is triggered when the blur (event) = > {}, // Native keyUP event keyUP (event)=>{}, // Native KeyDown event KeyDown (event)=>{}, // Native KeyPress event keyPress (event)=>{},}, Validate :[{required: true, message: 'please enter goods_name', trigger: 'blur'},],}Copy the code
Validate form validation rule: github.com/yiminghe/as…
Radio radio buttons
radioRule : {type:" postage", title:" postage",// label name field:"is_postage",// value:"0",//input value, Options :[{value:"0",label:" no support ",disabled:false}, {value:"1",label:" support ",disabled:true},], props: props {"type":undefined, // Optional value is button or not, for button style "size":"default", // single box size, The value can be large, small, default, or without setting "vertical":false, // Whether the options are arranged vertically, invalid in button style}, event:{// Triggered when the option status changes, returns the current state. Changing external data does not trigger change:(... arg)=>{}, }, validate:[], }Copy the code
The checkbox checkbox
checkboxRule : {type: "checkbox", the title: "label", / / label name field: "label", / / field names value: [" 1 ", "2", "3"), / / input value, Options :[{value:"1",label:" useful ",disabled:true}, {value:"2",label:" convenient ",disabled:false}, {value: "3", the label: "practical", disabled: false}, {value: "4", the label: "effective", disabled: false},], props: {"size":"default", // Select the size of the box group. The value can be large, small, default, or not set.}, event:{// This parameter is valid only when used alone. Trigger when the option state changes. Change is not triggered when external data changes :(... arg)=>{}, }, validate:[], }Copy the code
The switch switch
SwitchRule: {type:"switch", title:" is_show",// label name field:"is_show",// input value:"1",//input value, props: {"size":"default", // The size of the switch, the value can be large, small, default or no. It is recommended to use large if two characters are used. FalseValue :" falseValue":" false ", // Disables the switch "trueValue":"1", // Value at selected times, which can be useful when voting for a falseValue like 1 and 0 Useful when using things like 1 and 0}, slot: Close :" down ", // Custom display closed content}, //slot can not be configured event:{// switch changes when triggered, Returns the current state of 0 | 1 change: (bool) = > {},}, validate: [],}Copy the code
Select the selector
SelectRule: {type: "select", field: "cate_id", title: "product classification ", props: {"multiple": true, // If multiple" clearable": "Filterable ": true, // Whether search is supported // remote search is not supported yet // "remote": False, // "remote-method":Function, // "loading": false, // "loading-text": // select the size of the box (large, small, default, or placeholder); "Please select ", // Select box default text" not-found-text": "no matching data ", // display content when the drop-down list is empty "placement": }, value: ["104","105"], options: [{"value": "104", "label" : "ecological vegetables", "disabled" : false}, {" value ":" 105 ", "label" : "fresh fruit", "disabled" : False},], event:{// When the selected Option changes, Returns the value change: (checked) = > {}, / / search words change triggered when 'query - change: (keyword) = > {},}, validate: [],}Copy the code
DatePicker DatePicker
DatePickerRule: {type: "DatePicker", field: "section_day", title: "active date ", value: [1519110955000, new Date()], //input value, type is daterange, dateTimerange value is array [start_value,end_value] props: {"type": "Datetimerange ", // Display type, optional values are date, daterange, datetime, datetimerange, year, month "format": "Yyyy-mm-dd HH: MM :ss", // Display date format "placement": "Bottom-start ", // Where the date picker appears, The optional value is toptop-starttop-endbottombottom-startbottom-endleftleft-startleft-endrightright-startright-end "Placeholder ":" please select the time ", // placeholder text "confirm":false, // whether to display the bottom control bar, after opening, select the date, the selector will not be closed, only after user confirmation can be closed "size":"default", // size, The options are large, small, default, or "disabled":false, // Whether to disable the selector "clearable":true, // Whether to display the clear button "readonly":false, // Completely read-only, "Editable ":false, // Whether the text box can be}, event:{// Triggered when the date changes, the formatted date, Such as the 2016-01-01 change: (value) = > {}, / / the pop-up calendar and closing day last trigger true | false 'open - change: (bool) = > {}, // valid in confirm mode or clearable = true, clear when the date is cleared :(... arg)=>{}, }, validate:[], }Copy the code
TimePicker TimePicker
TimePickerRule: {type: "TimePicker", field: "section_time", title: "active time", value: [], //input value, type is timerange value is array [start_value,end_value] props: {"type": Timerange "format": "HH:mm:ss", // Display type: time, timerange" format": "HH:mm:ss", // Display time format: "steps": [], // Interval of the drop-down list. The three items of the array correspond to hours, minutes, and seconds. For example, if the value is set to [1, 15], 00, 15, 30, 45 minutes are displayed. "placement": "Bottom-start ", // the position where the time selector appears, The optional value is toptop-starttop-endbottombottom-startbottom-endleftleft-startleft-endrightright-startright-end "Placeholder ":" please select the time ", // placeholder text "confirm":false, // whether to display the bottom control bar, after opening, select the date, the selector will not be closed, only after user confirmation can be closed "size":"default", // size, The options are large, small, default, or "disabled":false, // Whether to disable the selector "clearable":true, // Whether to display the clear button "readonly":false, // Completely read-only, "Editable ":false" is not displayed,} can be entered in the text box, event:{// The formatted time is triggered when the time changes, Such as 09:41:00 change: (checked) = > {}, / / the pop-up float and close the floating layer is triggered when true | false 'open - change: (bool) = > {}, / / a clear date when trigger clear: (... arg)=>{}, }, validate:[], }Copy the code
InputNumber Indicates the number input box
InputNumberRule: {type: "InputNumber", field: "sort", title: "sort", value: 0, //input value props: {" Max ": Undefined, // undefined "min": undefined, // minimum "step": 1, // Each change can be decimal "size":"default", // input box size, The value can be large, small, or default, or "disabled":false. "readonly":false. "editable":true. // Whether to edit "precision":0, // value precision}, event:{// value change callback, Returns the current value change: (value) = > {}, / / focus triggered when focus: (event) = > {}, / / out-of-focus triggered when the blur (event) = > {},}, validate: [],}Copy the code
ColorPicker ColorPicker
ColorPickerRule: {type: "ColorPicker", field: "color", title: "color", value: '#ff7271', //input value: {"alpha": False, // Whether to support transparency "hue": true, // Whether to support color "recommend": False, // Whether to display the recommended color preset "size":"default", // the size can be large, small, default or not set "colors":[], // Custom color preset "format":"hex", // color format, The optional values are HSL, HSV, HEX, or RGB. If alpha is turned on, the value is RGB, and the other values are HEX}. Event :{ Change (color)=>{}, // Activate 'active-change':(color)=>{},}, validate:[],}Copy the code
Multistage tandem
cascaderRule: {type: "cascader", the title: "area", the field: "address", value: [' in shaanxi province ', 'xi', 'new'], props: {/ / optional data sources, Format reference example data: window. The province | | [], after selecting / / display function, RenderFormat :label => label.join('/'), // Whether selector is disabled disabled:false, // Whether clearable:true, // input box placeholder placeholder:' please select ', // secondary menu expansion mode, optional value is click or hover trigger:'click', // when this is true, the value of each level of the menu option will change, ChangeOnSelect :false, // Enter the size of the box, the value can be large or small or do not fill size:undefined, // dynamically obtain data, Loading loadData:()=>{}, // Whether to search for Filterable :false, // The content displayed when the search list is empty notFoundText:' No match ', // Whether to place the shell layer in the body, Transfer :false,}, event:{// Select the completed callback and return value value which is the selected value. Change (value, selectedData)=>{}, // trigger 'visible-change' when opening and closing popover :bool=>{}}, validate:[],}Copy the code
The Upload to Upload
UploadRule: {type: "Upload", field: "PIC ", title:" UploadRule ", value: ['http://img1.touxiang.cn/uploads/20131030/30-075657_191.jpg','http://img1.touxiang.cn/uploads/20131030/30-075657_191.jp G '], / / input value props: {"type":"select", // Upload control type, optional values are select (click select), drag (support drag) "uploadType":"image", // upload file type, optional values are image, File (upload file) "action": "", // Upload address, mandatory "headers": {}, // set the upload request header "multiple": True, // Support multiple selection of files "data":{}, // with the additional parameter "name":"", // Upload the file field name" withCredentials":false, ShowUploadList :false, // Whether to display the list of uploaded files // "defaultFileList":[], // Default list of uploaded files "accept":"", Format :[], // Supports file types. Unlike Accept, format is a suffix that recognizes files. Accept is the native Accept attribute of the input tag. "MaxSize ":undefined, // file size limit, in KB "maxLength":1, "beforeUpload":()=>{}, // Hook before uploading the file, parameter is the uploaded file, If false or Promise is returned stop uploading "onProgress":()=>{}, // hook for file uploading, The return fields are event, file, fileList "onSuccess":function () { return 'http://img1.touxiang.cn/uploads/20131030/30-075657_191.jpg'; }, // Hook for successful file upload, $f.uploadpush (field,filePath) to add the uploaded path to value. "onError":(error, file, fileList)=>{}, // hook for failed file upload with error, file, fileList "onPreview":()=>{}, hook for failed file upload with file, "OnRemove ":()=>{}, // list of files to remove the hook, Return field file, fileList "onFormatError":()=>{}, // hook for failed file format validation, Return fields: file, fileList "onExceededSize":()=>{}, // hook for files exceeding the specified size limit, return fields: file, fileList},}Copy the code
Accept File type: developer.mozilla.org/en-US/docs/…
Globally configure createOptions
Document. body el:null, //form configures form:{// Whether to enable inline form mode inline:false, // The position of the form field tag, Optional values are left, right, top labelPosition:'right', // width of the field label, All formItems inherit the Form component's label-width value, labelWidth:125, showMessage:true, // native autocomplete, Optional values are off or on autocomplete:'off',}, upload:{// Hook before uploading file, parameter is uploaded file, Stop uploading if false or Promise is returned. BeforeUpload :()=>{}, // hook for file uploading, Return fields are event, file, fileList onProgress:(event, file, fileList)=>{}, // hook for successful file upload, OnSuccess :(response, file, fileList)=>{// return filePath; }, // if the file fails to upload, fileList onError:(error, file, fileList)=>{}, // if the file fails to upload, fileList onError:(error, file, fileList)=>{}, OnPreview :(file)=>{}, // list of files to remove the hook when the file, The return field is file, fileList onRemove:(file, removeFn)=>{removeFn(); FileList onFormatError:(file, fileList)=>{}, fileList onFormatError:(file, fileList)=>{}, Return field file, fileList onExceededSize:(file, fileList)=>{}, // Action button icon, set to false will not display handleIcon:'ios-eye-outline', AllowRemove :true}, // Form submit event onSubmit:(formData)=>{}, SubmitBtn :{// Button type, Possible values are primary, ghost, bootstrap, text, info, success, warning, error, or not set type:"primary", // button size, Size :"large", // button shape, circle or shape:undefined, // Long :true, // Set the button's native type, HtmlType :"button", // Set the button to be disabled. Disabled :false, // Set the button icon type icon:"ios-upload", InnerText :" Commit ", // Set the button to loading state loading:false}}Copy the code
Time format
The name of the | instructions | The sample |
---|---|---|
yyyy | Year (four digits) | 2016 |
yy | Year (two digits) | 16 |
MM | Month (two persons) | 01 |
M | Month (one) | 1 |
MMMM | Month (English) | January |
MMM | Month – Month | Jan |
dd | Date (two digits) | 01 |
d | Date (one digit) | 1 |
Do | Date – Abbreviation | 1st |
DD | Week (two persons) | 00 |
D | Week (one) | 0 |
dddd | Week (English) | Monday |
ddd | Week (in English) | Mon |
HH | Hours (two digits in 24 hours) | 01 |
H | Hour (one in 24 hours) | 1 |
hh | Hours (two digits in 12-hour system) | 01 |
h | Hours (12 hours per person) | 1 |
mm | Minutes (two persons) | 01 |
m | Minutes (one person) | 1 |
ss | Seconds (two digits) | 01 |
s | Second (one digit) | 1 |
SSS | Ms (three digits) | 019 |
SS | Ms (two digits) | 01 |
S | Ms (one bit) | 1 |
A | Morning and afternoon (capital letters) | AM/PM |
a | Morning and afternoon (lowercase) | am/pm |
ZZ | The time zone | + 0800 |
The above are the date formats supported by iView. You can freely combine the types you need, for example:
- Yyyy: January 1, 2016
- MM/dd/yy: 12/24/16
- H dot M minute s second: 9:41:0 second