Author: Little potato Biubiubiu

Blog Park: www.cnblogs.com/HouJiao/

The Denver nuggets: juejin. Cn/user / 243617…

Wechat official account: Tudou Mother’s Broken thoughts (scan code attention, suck cats together, listen to stories together, learn front-end technology together)

Code word is not easy, praise to encourage yo ~

preface

This article focuses on experimenting with the Form component in Element.

The content of this article is relatively simple, basically referring to the document to practice part of the content of the form, and will continue to update some common functions of the form.

In the meantime, the next article, Element Form Practices (part 2), will share a Form practice in project development and document some of the problems encountered during this process.

Project environment

In order to be simple and fast, I set up the development environment of the project by introducing CDN static resources.

<! -- index.html --> <! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0"> <title>Element Form practice </title> <! -- vue: development environment version, including helpful command line warnings --> <script SRC ="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <! -- Element: Introduce style --> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <! -- Element: Introduces the component library --> <script SRC ="https://unpkg.com/element-ui/lib/index.js"></script>
    
</head>
<body>
    <div id="box">
        <span> {{message}} </span>
        <el-divider></el-divider>
    </div>
    <script>
        var vm = new Vue({
            el: '#box',
            data: {
                message: "Element Form Practice"
            }
        })
    </script>
</body>
</html>
Copy the code

Once the environment is ready, open the page locally and see the results.

Next, let’s get started with the Element Form.

Using the Form component

Typical form

Let’s first practice a typical form according to the official documentation.

The complete code for a typical form looks like this:

<! -- index.html -->

      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>The Element Form practice</title>
    <! -- Development environment version, including helpful command line warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <! -- Introducing styles -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <! -- Introducing a component library -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    
</head>
<body>
    <div id="box">
        <span> {{message}} </span>
        <el-divider></el-divider>
        <! -- Typical form -->
        <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="Activity Name">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="Active area">
                <el-select v-model="form.region" placeholder="Please select the active area.">
                <el-option label="Zone one" value="shanghai"></el-option>
                <el-option label="Area two" value="beijing"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="Active Time">
                <el-col :span="11">
                <el-date-picker type="date" placeholder="Select date" v-model="form.date1" style="width: 100%;"></el-date-picker>
                </el-col>
                <el-col class="line" :span="2">-</el-col>
                <el-col :span="11">
                <el-time-picker placeholder="Choose the time" v-model="form.date2" style="width: 100%;"></el-time-picker>
                </el-col>
            </el-form-item>
            <el-form-item label="Instant delivery">
                <el-switch v-model="form.delivery"></el-switch>
            </el-form-item>
            <el-form-item label="Nature of activity">
                <el-checkbox-group v-model="form.type">
                <el-checkbox label="Food/Restaurant Online Activities" name="type"></el-checkbox>
                <el-checkbox label="Ground pushing activity" name="type"></el-checkbox>
                <el-checkbox label="Offline Themed Activities" name="type"></el-checkbox>
                <el-checkbox label="Pure brand exposure" name="type"></el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="Special Resources">
                <el-radio-group v-model="form.resource">
                <el-radio label="Online Brand Sponsorship"></el-radio>
                <el-radio label="Offline venue free"></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="Form of activity">
                <el-input type="textarea" v-model="form.desc"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">Immediately create</el-button>
                <el-button>cancel</el-button>
            </el-form-item>
        </el-form>
    </div>
    <script>
        var vm = new Vue({
            el: '#box'.data: {
                message: "Element Form Practice".form: {
                    name: ' '.// Activity name
                    region: ' '.// Active area
                    date1: ' '.// Activity time - date
                    date2: ' '.// Activity time - time
                    delivery: false.// Instant delivery
                    type: [],         // Activity nature
                    resource: ' '.// Special resources
                    desc: ' '          // Activity format}},methods: {
                onSubmit() {
                    console.log('submit! '); }}})</script>
</body>
</html>
Copy the code

Browser opening page:

You can see that the form component is displayed on the page.

Next, let’s look at some of the important features of this form component.

The form properties

Form attributes refer to attributes that are set on the el-Form element

model

The previous use of the model attribute is as follows:

<! -- Typical form -->
<el-form ref="form" :model="form" label-width="80px">

</el-form>
Copy the code

The Model property is the form data, and it binds the form data as follows:

form: {
    name: ' '.// Activity name
    region: ' '.// Active area
    date1: ' '.// Activity time - date
    date2: ' '.// Activity time - time
    delivery: false.// Instant delivery
    type: [],         // Activity nature
    resource: ' '.// Special resources
    desc: ' '          // Activity format
}
Copy the code

Each item in the form data corresponds to an el-form-item item in the form. For example, if name corresponds to the activity name, then el-form-item is written as follows:

<el-form-item label="Activity Name">
    <el-input v-model="form.name"></el-input>
</el-form-item>
Copy the code

Note that the v-Model for the form control el-Input is not bound to the el-form-item: The INPUT control corresponds to el-Input, and the V-Model is bound to El-Input and the SELECT control corresponds to El-Select The checkbox control corresponds to el-Checkbox-group +el-checkbox, and v-Model is bound to el-Checkbox-group Radio control corresponds to el-radio-Group + EL-Radio, and V-Model is bound to el-Radio =group. Switch Control corresponds to El-Switch, and V-Model is bound to El-Switch

Form data bound to model

Next, let’s explore the form data.

To explore the form data, you need to do three things:

01: Print form data in onSubmit function bound to "Create now" button 02: fill in form information 03: click "Create Now" button to view the print result of form dataCopy the code

Step 1: Print the form data in the onSubmit function that creates the button binding immediately.

methods: {
    onSubmit() {
        console.log(this.form); }}Copy the code

Step 2: Fill in the form information.

Step 3: Click the Create Now button to view the form data print results.

As you can see, the form data contains the contents of our form. I’ll tease out the relationship between the fields in the form, their values, and the form controls.

Properties/fields describe Control types value The source of value type
name The name of the event input “Element Form Practice” inputEnter the contents of the box String
region Active area select “shanghai” The selectedselectThe value of the value String
date1 Activity time – date el-time-picker Thu May 07 2020 00:00:00 GMT+0800 The date control selects Date
date2 Activity time – time el-time-picker Thu May 07 2020 18:24:39 GMT+0800 Time control selects the content Date
delivery Instant delivery el-switch true Switch selection result Boolean
type Nature of the activities checkbox [” Food/Restaurant Online Campaign “,” Ground Campaign “] The selectedcheckboxThe label value Boolean
resource Special resources radio “Online Brand Sponsorship” The selectedradioThe label value String
desc Activity form input “Other” inputInput box content String

It can be seen that the form data bound by the model attribute of the form el-Form is consistent with the content in the form. Therefore, in daily project development, after the form information is filled in, click the submit button to directly send this. Form as the parameter of the request to the backend.

However, it is necessary to make some improvements to the this.form data.

In the previous code, the type and resource values in the final form are the result of Chinese data, which is passed to the back end, which is very unfriendly to the logic of the back end.

Therefore, in daily project development, the front and back end will have a default convention relationship for such data:

// Activity nature
{   'foodOnlineActivities': 'Food/Restaurant Online Activities'.'earthPushingActivity': 'Ground push'.'offlineThemeActivities': 'Offline Themed Activities'.'brandExposure': 'Pure brand exposure',}// Activity format
{   'online': 'Food/Restaurant Online Activities'.'offline': 'Ground push'
}
Copy the code

Or in simpler conventions:

// Activity nature
{   'foodOnlineActivities': '1'.'earthPushingActivity': '2'.'offlineThemeActivities': '3'.'brandExposure': '4',}// Activity format
{   'online': '1'.'offline': '2'
}
Copy the code

Our front-end code needs to be modified as follows:

<el-form-item label="Nature of activity" prop="type">
    <el-checkbox-group v-model="form.type">
        <el-checkbox label="1" name="type">Food/restaurant online events</el-checkbox>
        <el-checkbox label="2" name="type">To push the activity</el-checkbox>
        <el-checkbox label="3" name="type">Offline themed activities</el-checkbox>
        <el-checkbox label="4" name="type">Pure brand exposure</el-checkbox>
    </el-checkbox-group>
</el-form-item>
<el-form-item label="Special Resources" prop="resource">
    <el-radio-group v-model="form.resource">
        <el-radio label="1">Sponsored by online brands</el-radio>
        <el-radio label="2">Offline venue free</el-radio>
    </el-radio-group>
</el-form-item>
Copy the code

Select the corresponding option and view the result of the form data:

After the modified form data is transferred to the back end, it is relatively simple to save the data or judge the logic, and there will be no problems due to the Chinese encoding.

The last point about form data is the form’s initial value.

When we see that form data defaults to null values (form fields are of different types, and the above initial values are collectively referred to as null values), we can actually specify a default value for form. Xx directly in data.

Here, restore the values of type and resource set above to Chinese, remember to set them in the above form during project development.

 form: {
    name: 'I am the name of the activity that initializes the Settings'.// Activity name
    region: 'beijing'.// Active area
    date1: new Date(),                // Activity time - date
    date2: new Date(),                // Activity time - time
    delivery: true.// Instant delivery
    type: ['Pure brand exposure'].// Activity nature
    resource: 'Online Brand Sponsorship'.// Special resources
    desc: 'I'm the activity form of the initialization Settings'  // Activity format
}
Copy the code

After setting the default values, we refresh the page and the contents of the form are the values we set.

Note: For select, checkbox, and Radio, the value in the form field must be the same as the value of the corresponding control’s Label. Otherwise, the control will not match and the corresponding content will not be backfilled into the form.

rules

The form attribute rules is used to set the validation rules for the form, so let’s put it into practice.

<! -- index.html -->
<el-form ref="form" :model="form" :rules="addFormRules" label-width="80px">

    <! -- unmodified code omitted -->
    
</el-form>
Copy the code

As you can see :rule applies to the el-form and binds a variable addFormRules.

We then write a validation rule for the activity name name in addFormRules.

// Some unmodified code is omitted
var vm = new Vue({
    el: '#box'.data: {
        addFormRules: {
            name: [{
                required: true.// Name specifies whether the value is mandatory. True: mandatory false: optional
                trigger: 'blur'.Blur: Validate rules when elements lose focus
                message: "Please enter an activity name".// If there is no error message}, {min: 5.// Minimum field length
                max: 10.// Maximum field length
                trigger: 'blur'.Blur: Validate rules when elements lose focus
                message: "Activity name is 5-10 characters long".// Error message displayed when the rule is not met}}}}])Copy the code

In addFormRules we define the name field, which is an array, each of which is a JSON. For the validation rule we wrote, the first JSON element in the array writes the mandatory validation rule for the active name field. The meaning of each key/value pair in the JSON is noted in the annotation; The second JSON element in the array writes a length validation rule for the active name field.

So here’s the most important step for our rule to take effect: set the prop property on the el-Form-Item.

<! -- index.html -->
<el-form ref="form" :model="form" :rules="addFormRules" label-width="80px">

    <el-form-item label="Activity Name" prop="name">
        <el-input v-model="form.name"></el-input>
    </el-form-item>
    
    <! -- unmodified code omitted -->
    
</el-form>
Copy the code

As you can see, the prop property value is the name field defined in the form. Only then can the validation rule for name defined in addFormRules be associated with the corresponding form, otherwise the validation rule will not take effect.

It is important to note that the fields in the form data bound to the el-Form form, the values set by prop, and the fields in the addFormRules data bound to the RULE must all be the same. Otherwise, validation problems will occur.

Label-position, label-width, and label-suffix

All three form properties are labels that set the form field.

Label-position Sets the alignment mode of label fields (right alignment by default). Label-width Specifies the label field width. Label-suffix Sets the suffix of a label domain.

 <el-form 
    ref="form" 
    :model="form" 
    :rules="addFormRules" 
    label-position="left"
    label-width="120px"
    label-suffix=":">
    
    <! -- unmodified code omitted -->
    
</el-form>
Copy the code

status-icon

 <el-form 
    ref="form" 
    :model="form" 
    :rules="addFormRules" 
    label-width="120px"
    status-icon="true">
    
    <! -- unmodified code omitted -->
    
</el-form>
Copy the code

Form method

validate

The form method validate is a method that validates the entire form with a callback function.

The callback function is called after the verification is complete, passing in two parameters: whether the verification succeeded and the field that failed. If the callback function is not passed in, a Promise is returned.

Let’s put this form method into practice.

The main change is to call the validate method when submitting the form, printing out two arguments to the callback function.

<el-form 
    ref="form" 
    :model="form" 
    :rules="addFormRules"
    label-width="120px"
    label-suffix=":"
    :status-icon="statusIcon">
    
    <! -- unmodified code omitted -->
    <el-form-item>
        <el-button type="primary" @click="onSubmit">Immediately create</el-button>
        <el-button>cancel</el-button>
    </el-form-item>
</el-form>
<script>
var vm = new Vue({
    el: '#box'.data: {
        message: "Element Form Practice".statusIcon: true.form: {
            name: 'I am the name of the activity that initializes the Settings'.// Activity name
            region: 'beijing'.// Active area
            date1: new Date(),  // Activity time - date
            date2: new Date(),  // Activity time - time
            delivery: true.// Instant delivery
            type: ['Pure brand exposure'].// Activity nature
            resource: 'Online Brand Sponsorship'.// Special resources
            desc: 'I'm the activity form of the initialization Settings'          // Activity format
        },
        addFormRules: {
            name: [{
                required: true.// Name specifies whether the value is mandatory. True: mandatory false: optional
                trigger: 'blur'.Blur: Validate rules when elements lose focus
                message: "Please enter an activity name".// If there is no error message}, {min: 5.// Minimum field length
                max: 10.// Maximum field length
                trigger: 'blur'.Blur: Validate rules when elements lose focus
                message: "Activity name is 5-10 characters long".// Error message displayed when the rule is not met}}},methods: {
        onSubmit() {
            this.$refs['form'].validate((validate,failedInfo) = > {
                console.log('validate:')
                console.log(validate);
                console.log('failedInfo:')
                console.log(failedInfo); }}}})</script>
Copy the code

Print results of validate and failedInfo when the form validates successfully:

Print result of validate and failedInfo when form validation fails:

Previously, we only wrote the validation rule for the name field, so when the validate method is called in the form submission, only the name field is validated.

In fact, for our daily development, we pay more attention to the first parameter. When the first parameter in the callback function is true, it means that the form verification is successful, and the form data can be passed to the back end. Instead, if the first parameter is falses, the form has failed to validate and we can give the user an error message.

methods: {
    onSubmit() {
        this.$refs['form'].validate((validate,failedInfo) = > {
            if(validate){
                // Send form data to the back end
                // Send a POST request
                axios.post(url, this.form).then(function (response) {
                    // Process the response data returned by the back end
                    
                });
             }else{
                // Prompt the user
                this.$message({
                    message: 'Form data format is wrong, please check and resubmit.'.type: "error".center: true}); }}}})Copy the code

It is important to note that the callback function is best written as an arrow function, so that the this inside the callback represents the Vue instance object. If you use the normal function declaration function, the this inside the callback refers to a Windows object.

resetFields

The form property resetFields resets the entire form, resetting all field values to their original values and removing validation results.

This change changes the cancel button to the reset button and calls the resetFields method when the reset button is clicked.

<el-form 
    ref="form" 
    :model="form" 
    :rules="addFormRules"
    label-width="120px"
    label-suffix=":"
    :status-icon="statusIcon">
    
    <! -- unmodified code omitted -->
    
    <el-form-item>
        <el-button type="primary" @click="onSubmit">Immediately create</el-button>
        <el-button type="primary" @click="resetForm">reset</el-button>
    </el-form-item>
</el-form>
<script>
var vm = new Vue({
    el: '#box'.data: {
        message: "Element Form Practice".statusIcon: true.form: {
            name: 'I am the name of the activity that initializes the Settings'.// Activity name
            region: 'beijing'.// Active area
            date1: new Date(),  // Activity time - date
            date2: new Date(),  // Activity time - time
            delivery: true.// Instant delivery
            type: ['Pure brand exposure'].// Activity nature
            resource: 'Online Brand Sponsorship'.// Special resources
            desc: 'I'm the activity form of the initialization Settings'          // Activity format
        },
        addFormRules: {
            name: [{
                required: true.// Name specifies whether the value is mandatory. True: mandatory false: optional
                trigger: 'blur'.Blur: Validate rules when elements lose focus
                message: "Please enter an activity name".// If there is no error message}, {min: 5.// Minimum field length
                max: 10.// Maximum field length
                trigger: 'blur'.Blur: Validate rules when elements lose focus
                message: "Activity name is 5-10 characters long".// Error message displayed when the rule is not met}}},methods: {
        onSubmit() {
            this.$refs['form'].validate((validate,failedInfo) = > {
                console.log('validate:')
                console.log(validate);
                console.log('failedInfo:')
                console.log(failedInfo);
            })
        },
        resetForm(){
            this.$refs['form'].resetFileds(); }}})</script>
Copy the code

A closer look at the reset results shows that only the values of the active name field are restored to their original values, while the rest of the Spaces where we modified the form information are not reset to their original values.

Note that the resetFileds method sets the value of the form to an initial value, not a null value. The initial value is the value that was set in the component’s data, so when we hit reset the value of the active name space goes back to the activity name that I was initializing.

The effect is clearly wrong.

But the reason is simple: we didn’t set the prop property for the other form entries. Note that when using resetFileds, we must set the prop value for the form item el-form-item, otherwise we cannot reset it.

<el-form 
    ref="form" 
    :model="form" 
    :rules="addFormRules"
    label-width="120px"
    label-suffix=":"
    :status-icon="statusIcon"
    >
    <el-form-item label="Activity Name" prop="name">
        <el-input v-model="form.name"></el-input>
    </el-form-item>
    <el-form-item label="Active area" prop="region">
        <el-select v-model="form.region" placeholder="Please select the active area.">
            <el-option label="Zone one" value="shanghai"></el-option>
            <el-option label="Area two" value="beijing"></el-option>
        </el-select>
    </el-form-item>
    <el-form-item label="Active Time" >
        <el-col :span="11">
            <el-form-item prop="date1">
                <el-date-picker type="date" placeholder="Select date" v-model="form.date1" style="width: 100%;"></el-date-picker>
            </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col> 
        <el-col :span="11">
            <el-form-item prop="date2">
                <el-time-picker placeholder="Choose the time" v-model="form.date2" style="width: 100%;"></el-time-picker>   
            </el-form-item>
        </el-col>
    </el-form-item>
    <el-form-item label="Instant delivery" prop="delivery">
        <el-switch v-model="form.delivery"></el-switch>
    </el-form-item>
    <el-form-item label="Nature of activity" prop="type">
        <el-checkbox-group v-model="form.type">
            <el-checkbox label="Food/Restaurant Online Activities" name="type"></el-checkbox>
            <el-checkbox label="Ground pushing activity" name="type"></el-checkbox>
            <el-checkbox label="Offline Themed Activities" name="type"></el-checkbox>
            <el-checkbox label="Pure brand exposure" name="type"></el-checkbox>
        </el-checkbox-group>
    </el-form-item>
    <el-form-item label="Special Resources" prop="resource">
        <el-radio-group v-model="form.resource">
            <el-radio label="Online Brand Sponsorship"></el-radio>
            <el-radio label="Offline venue free"></el-radio>
        </el-radio-group>
    </el-form-item>
    <el-form-item label="Form of activity" prop="desc">
        <el-input type="textarea" v-model="form.desc"></el-input>
    </el-form-item>
    <el-form-item>
        <el-button type="primary" @click="onSubmit">Immediately create</el-button>
        <el-button type="primary" @click="resetForm">reset</el-button>
    </el-form-item>
</el-form>
Copy the code

The special note here is to set the prop property for the active time form item.

<el-form-item label="Active Time" >
    <el-col :span="11">
        <el-form-item prop="date1">
            <el-date-picker type="date" placeholder="Select date" v-model="form.date1" style="width: 100%;"></el-date-picker>
        </el-form-item>
    </el-col>
    <el-col class="line" :span="2">-</el-col> 
    <el-col :span="11">
        <el-form-item prop="date2">
            <el-time-picker placeholder="Choose the time" v-model="form.date2" style="width: 100%;"></el-time-picker>
        </el-form-item>
    </el-col>
</el-form-item>
Copy the code

Add an el-form-item element to the outer layer of the el-date-picker, compared to the previous code that did not set prop. That makes sense, too, because the active time contains two el-time-pickers bound to different form data: date1 and date2. A prop can only be set to one value, so element provides the solution of nesting a layer of el-form-item elements for both el-time-pickers. This allows you to set the prop properties separately.

Now let’s take a look at the reset button.

You can see that all the form entries reset successfully.

Form item attributes

A form item property is a property that’s set on an El-form-item and I’m just going to declare a few names just so you don’t get confused when you’re describing a form, the corresponding element is an el-form when you’re describing a form item

prop

This property was used earlier when we practiced form validation and form reset.

Form validation and form reset are a common feature in daily development, so it is necessary to set the prop property to form items when writing code to avoid confusing errors.

Be sure to set the value of the prop property to the name of the field bound to the form

label

The label attribute sets the text description of the form’s label field.

size

The size of the form component, with three optional values: medium/small/mini.

rules

Here rules is the validation rule for the form item, and now we validate the activity name field.

The main change is to remove rules from the form attribute el-Form and add rules rule validation to the el-Form-Item corresponding to the activity name.


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>The Element Form practice</title>
    <! -- Development environment version, including helpful command line warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <! -- Introducing styles -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <! -- Introducing a component library -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    
</head>
<body>
    <div id="box">
        <span> {{message}} </span>
        <el-divider></el-divider>
        <! -- Typical form -->
        <el-form 
            ref="form" 
            :model="form" 
            label-width="120px"
            label-suffix=":"
            :status-icon="statusIcon">
            <el-form-item 
                label="Activity Name" 
                prop="name" 
                :rules="[{required: true,trigger: 'blur',message: 'Please enter activity name '}]">
                <el-input v-model="form.name" ></el-input>
            </el-form-item>
            <el-form-item label="Active area" prop="region">
                <el-select v-model="form.region" placeholder="Please select the active area.">
                    <el-option label="Zone one" value="shanghai"></el-option>
                    <el-option label="Area two" value="beijing"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="Active Time" >
                <el-col :span="11">
                    <el-form-item prop="date1">
                        <el-date-picker type="date" placeholder="Select date" v-model="form.date1" style="width: 100%;"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col class="line" :span="2">-</el-col> 
                <el-col :span="11">
                    <el-form-item prop="date2">
                        <el-time-picker placeholder="Choose the time" v-model="form.date2" style="width: 100%;"></el-time-picker>   
                    </el-form-item>
                </el-col>
            </el-form-item>
            
            <el-form-item label="Instant delivery" prop="delivery">
                <el-switch v-model="form.delivery"></el-switch>
            </el-form-item>
            <el-form-item label="Nature of activity" prop="type">
                <el-checkbox-group v-model="form.type">
                    <el-checkbox label="Food/Restaurant Online Activities" name="type"></el-checkbox>
                    <el-checkbox label="Ground pushing activity" name="type"></el-checkbox>
                    <el-checkbox label="Offline Themed Activities" name="type"></el-checkbox>
                    <el-checkbox label="Pure brand exposure" name="type"></el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="Special Resources" prop="resource">
                <el-radio-group v-model="form.resource">
                    <el-radio label="Online Brand Sponsorship"></el-radio>
                    <el-radio label="Offline venue free"></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="Form of activity" prop="desc">
                <el-input type="textarea" v-model="form.desc"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">Immediately create</el-button>
                <el-button type="primary" @click="resetForm">reset</el-button>
            </el-form-item>
        </el-form>
    </div>
    <script>
        var vm = new Vue({
            el: '#box'.data: {
                message: "Element Form Practice".statusIcon: true.form: {
                    name: 'I am the name of the activity that initializes the Settings'.// Activity name
                    region: 'beijing'.// Active area
                    date1: new Date(),  // Activity time - date
                    date2: new Date(),  // Activity time - time
                    delivery: true.// Instant delivery
                    type: ['Pure brand exposure'].// Activity nature
                    resource: 'Online Brand Sponsorship'.// Special resources
                    desc: 'I'm the activity form of the initialization Settings'          // Activity format
                },
                addFormRules: {
                    name: [{
                        required: true.// Name specifies whether the value is mandatory. True: mandatory false: optional
                        trigger: 'blur'.Blur: Validate rules when elements lose focus
                        message: "Please enter an activity name".// If there is no error message}, {min: 5.// Minimum field length
                        max: 10.// Maximum field length
                        trigger: 'blur'.Blur: Validate rules when elements lose focus
                        message: "Activity name is 5-10 characters long".// Error message displayed when the rule is not met}}},methods: {
                onSubmit() {
                    this.$refs['form'].validate((validate,failedInfo) = > {
                        if(validate){
                            // Send form data to the back end
                            // Send a POST request
                            axios.post(url, this.form).then(function (response) {
                                // Process the response data returned by the back end

                            });
                         }else{
                            // Prompt the user
                            this.$message({
                                message: 'Form data format is wrong, please check and resubmit.'.type: "error".center: true
                            });
                       }
                    })
                },
                resetForm(){
                    this.$refs['form'].resetFields(); }}})</script>
</body>
</html>
Copy the code

The main code is as follows:

<el-form-item 
    label="Activity Name" 
    prop="name" 
    :rules="[{required: true,trigger: 'blur',message: 'Please enter activity name '}]">
    <el-input v-model="form.name" ></el-input>
</el-form-item>
Copy the code

You can see that the syntax of the validation rule added to the form item el-form-item is basically the same as that added to the form el-Form.

Now let’s look at the results of the validation.

You can see that the validation rules are in effect.

Finally, there is one more operation that we want to verify, which is to set rules on both el-Form and el-form-item.

<el-form 
    ref="form" 
    :model="form" 
    label-width="120px"
    label-suffix=":"
    :status-icon="statusIcon"
    :rules="addFormRules">
    <el-form-item 
        label="Activity Name" 
        prop="name" 
        :rules="[{required: true,trigger: 'blur',message: 'Please enter activity name '}]">
        <el-input v-model="form.name" ></el-input>
    </el-form-item>
</el-form>
Copy the code

You can see that I have added the rules back from the el-Form.

The validation rule for the active name field on the EL-Form is that it cannot be empty and is 5-10 characters long, whereas the rule set on the EL-item-form is that only content cannot be empty.

Let’s look at the results again.

You can see that only the non-null validation rule is in effect, but the length validation rule is not. Therefore, the conclusion is that rules on the EL-Form have a lower priority than rules rule validation on the El-Item-Form. When there are validation rules for fields defined on the El-Form-Item, the validation rules for fields defined on the corresponding El-Form will be ignored.

conclusion

This is the end of this article, the content is very simple.

The next article will share a form practice in project development and document some of the problems encountered along the way.

about

The author

Small potatoes biubiubiu

For a hard-working front-end novice, knowledge is limitless. Believe that you can always get where you want as long as you don’t stop learning

At the same time, I am also a person who likes small cats. There is a beautiful short female cat named Potato at home

Blog garden

www.cnblogs.com/HouJiao/

The Denver nuggets

Juejin. Cn/user / 243617…

Wechat official account

Potato mama’s mumbo jumbo

The original purpose of the wechat official account is to record some stories about myself and people around me, while updating some technical articles from time to time

Welcome to scan code attention, suction cat, listen to stories, learn front-end technology together

The author remarks

Small summary, welcome everyone guidance ~