preface

The object of this sharing is for non-professional front-end developers, such as testing/back-end and so on sometimes need to complete the front-end page, its front-end technology does not need in-depth understanding, only need to be able to quickly develop the front-end page according to the document. So I’m not going to go into the technical details, but just a quick way to build a front-end project.

The content of this share is based on Vue(2.x) + Element-UI quickly build the front page experience to share, this share will build a form page to demonstrate the entire creation process.

Through this sharing, we will introduce the following points:

* Environment setup * Quick VUE project creation * Route configuration * Directory structure Introduction * Create page * Application of elementUI form related components * linkageCopy the code

Environment set up

Use the Vue CLI tool to quickly create Vue projects

First install the Vue CLI (if the Node environment has been installed).

npm install -g @vue/cli
Copy the code

After the installation is complete, run the following command to check whether the installation is successful:

vue --version
Copy the code

Quickly create a VUE project

Quickly create a Vue project using the Vue CLI tool

Vue Create form-demo (name of project to create)Copy the code

After all the default operations are completed, go to the form-demo directory

cd form-demo
Copy the code

Element, a vUe-based desktop component library, provides a rich set of UI components that make front-end page development easier.

Install elementui

vue add element
Copy the code

Again, check the default all the way

After the installation, you can see that there is a plugins folder in the directory

There is an element.js that holds the configuration for the element to register as a global component

The following

And then let’s run that

npm run serve
Copy the code

Note: What command can be executed to start the service to view the configuration of scripts in the package.json file in the project root directory

NPM run * is used to perform services such as server(starting) buld(packaging)

When the execution is complete, the console displays the front-end page preview address

The following page is displayed

Our previous configuration is successful when we see the Element button display properly on the page

The routing configuration

And then there’s the question, right? What if I have a lot of pages?

This leads to the front-end route vue-router

The Vue Router is the official route manager of vue. js. Its deep integration with the vue.js core makes building a single page application a breeze.

Install the vue – the router

vue add router
Copy the code

After the installation is complete, you do not need to configure another router folder

The index.js is used to store the route configuration

The following configuration is found in index.js

{
    path: '/about'.name: 'About'.// route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () = > import(/* webpackChunkName: "about" */ '.. /views/About.vue')}Copy the code

We through the browser to http://localhost:8080/about to verify whether the routing installation is successful

The About page is accessible, indicating that all of our configurations are in effect

Introduction to directory Structure

The directory structure developed by THE VUE project needs to be easy to understand, build and manage, and facilitate future maintenance and reading by other colleagues.

The main directory for front-end development is in the SRC directory

  • componentsThe directory mainly holds common components (such as upload components, double-encapsulated popover components, etc.)
  • routerThe directory stores configurations related to routes
  • viewsStore page views (page views can also have the following specifications)
├─ views ├─ course // ├─ index.htm │ ├─ assets │ ├─ icon.png │ ├─ components // │ ├─ index.vue │ ├─ index.vue │ ├─ index.vue │ ├─ index.vue │ ├─ index.vue │ ├─ index.vue │ ├─ index.vue │ ├─ index.vue │ ├─ index.vueCopy the code
  • App.vueIs the main component, the page entry file, all the pages are inApp.vueNext to switch
  • main.jsProgram entry file, initializationvueInstances and the introduction of required plug-ins and components (such as Element /vue-router) are inmain.jsRegistered in the

Create the page

Now that you have some idea of the directory structure, let’s create our own page

First we create a course folder under the views directory

Create another index.vue file

</div> </template> <script> export default {} </script> <style> </style>Copy the code

This is a basic page structure

The template contains the page template, which is updated through a data-driven view

Script stores data and logic processing related to specific services

Style contains the related styles of the page

Note: Template must have only one child; otherwise, the compiler will report an error. Other elements can be embedded in this child element.

Once the course page is created, how do you access it?

This requires configuring page routing

Open the/views/router/index. Js

First you need to bring in the course view (page)

import Course from '.. /views/course'
Copy the code

Use the “import” method to find the course page by path and import it (if the page view is named as index.vue under the folder, only need to import it to the folder level, if other names, need to import it to.vue file)

After importing routes, you need to configure specific routing information in routes:

const routes = [
  {
    path: '/'.name: 'Home'.component: Home
  },
  {
    path: '/about'.name: 'About'.// route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () = > import(/* webpackChunkName: "about" */ '.. /views/About.vue')}, {path: '/course'.name: 'Course'.component: Course
  }
]
Copy the code

Among them:

Path is the path to access

Name Indicates the name of the page. In addition to the path, the page can also be redirected by name (refer to the Vue-router document for details).

Component view, the course view introduced above

Configuration is completed, by visiting http://localhost:8080/course to see if successful

If the content of our page is displayed correctly, the route configuration is successful

Let’s take a look at app.vue again

As mentioned earlier, app.vue is the root component of the project, where all pages are switched

Element form component application

Now that we have a simple page created, we want to create a form page that includes text boxes, radio boxes, drop-down menus, submit buttons, and so on. And the need for linkage processing according to different options.

From the Element-UI documentation, we can write a perfect form:

<template> <div class="container"> <div class="title"> <el-form ref="form" class="create-course" :model="form" "> <el-form-item label=" ">< el-input v-model="form.name"></el-input> </el-form-item> <el-form-item label=" "> <el-radio :label="1"> </el-radio :label="2"> </el-radio> <el-radio :label="2"> </el-radio> <el-radio :label="3"> </el-radio> </el-radio-group> </el-form-item> <el-form-item label=" discipline "> <el-select v-model="form.subject" Placeholder =" please select the subject ">< el-option label=" high number "value="gaoshu"></el-option> <el-option label=" English" value="yingyu"></el-option> </ key-form > </ key-form > </ key-form > </ key-form > </ key-form > < el - button > cancel < / el - button > < / el - form - item > < / el - form > < / div > < / template >Copy the code
<script>
export default {
  data() {
    return {
      form: {
        name: ' '.grade: ' '.subject: ' '}}},methods: {
    onSubmit() {
      console.log('submit')
    }
  }
}
</script>
Copy the code
<style scoped>
.container {
  width: 900px;
  border: solid 1px #ccc;
  margin: 0 auto;
  text-align: left;
}
.title {
  line-height: 42px;
  padding-left: 24px;
  margin-bottom: 20px;
  border-bottom: solid 1px #ccc;
  text-align: left;
}
.create-course {
  padding: 24px 200px 24px 0;
}
</style>
Copy the code

Since the element component was previously registered globally in main.js, we can refer to it directly in the page instead of importing it in the page itself

Before dealing with the specifics of the business logic, let’s take a quick look at Vue’s bidirectional data binding

Vue’s biggest feature is data-driven. The simple understanding is that when data changes, the view changes accordingly, the developer does not need to change the DOM, and the page does not refresh. When the view changes (such as the text box content), the data bound to it also changes.

Vue’s bidirectional data binding is primarily achieved through data hijacking and a publisher-subscribe pattern, which doesn’t need to be explored.

Next, we need to add specific business logic to the course page, which needs to implement the following points:

  • The data of grade and subject are put in data, and the template is rendered in a loop to increase flexibility
  • Subjects are hidden by default, and different subject lists are displayed according to the selected grade
  • When submitting the form, check the required fields of course name, grade, and subject, as in the submission form
Grade and subject data are placed in data, and subject is hidden by default

Add gradeList and subjectList fields to data

gradeList: [
  {
  	id: 1.name: 'one'
  },
  {
  	id: 2.name: 'second'
  },
  {
  	id: 3.name: 'three'}].isShowSubject: false.subjectList: []
Copy the code

Dynamically render grade list, subject list through V-for in template

<el-form-item label=" grade: "> <el-radio-group v-model="form.grade"> <el-radio v-for="item in gradeList" :key="item.id" :label="item.id">{{ Item. Name}}</el-radio> </el-radio-group> </el-form-item> <el-form-item v-if="isShowSubject" label=" subject "> <el-select V -model="form.subject" placeholder=" placeholder "> <el-option V -for="item in subjectList" :key="item.id" :label="item.name" :value="item.id"></el-option> </el-select> </el-form-item>Copy the code

The loop needs to be traversed with v-for, and the loop needs to bind the key

To hide an item, just set v-if to false

Show different subject lists according to the selected grade
<el-form-item label=" grade: "> <el-radio-group v-model="form.grade" @change="handleChangeGrade"> <el-radio v-for="item in gradeList" :key="item.id" :label="item.id">{{ item.name }}</el-radio> </el-radio-group> </el-form-item>Copy the code

First, listen to the change event of grade, get the current grade ID, and then assign values to the subject list according to different ids, and display the subject list

// Methods
// Switch grades
    handleChangeGrade(id) {
      this.form.subject = ' ' // Clear the selected subjects each time you switch grades
      if (id === 1) { // Assign different values to each subject according to the annual leave ID
        this.subjectList = [
          {
            id: 11.name: 'advanced mathematics'
          },
          {
            id: 12.name: 'English'
          },
          {
            id: 13.name: 'Linear algebra'}}]else if(id === 2) {
        this.subjectList = [
          {
            id: 21.name: 'Computer networks'
          },
          {
            id: 22.name: 'C++'
          },
          {
            id: 23.name: 'Java'
          },
          {
            id: 24.name: 'Operating system'}}]else {
        this.subjectList = [
          {
            id: 31.name: 'Data structure'
          },
          {
            id: 32.name: 'assembly'}}]this.isShowSubject = true // Show the hidden subject}}Copy the code

This creates a linkage effect, showing different content according to different choices

The essence of linkage is to listen for changes in options and assign different values to the content that needs linkage according to different options, so as to achieve linkage effect through data-driven view update.

Submit the form and verify it

The Form component provides Form validation by passing in the convention validation rules via the Rules property and setting the form-item prop property to the name of the field to verify.

<el-form ref="form" :rules="rules" class="create-course" :model="form" label-width="140px"> <el-form-item label=" "Prop ="name"> <el-input v-model="form.name"></el-input> </el-form-item> <el-form-item label=" grade: " prop="grade"> <el-radio-group v-model="form.grade" @change="handleChangeGrade"> <el-radio v-for="item in gradeList" :key="item.id" :label="item.id">{{ item.name }}</el-radio> </el-radio-group> </el-form-item> <el-form-item V-if ="isShowSubject" label=" prop="subject"> <el-select v-model="form.subject" placeholder=" select subject"> <el-option v-for="item in subjectList" :key="item.id" :label="item.name" :value="item.id"></el-option> </el-select> </el-form-item> </el-form-item> </el-form-item> </el-form-item> </el-form-item> </el-form-item> </el-form>Copy the code
// Add "rules" to data
rules: {
  name: [{required: true.message: 'Please enter the course name'.trigger: 'blur' },
    { min: 3.max: 10.message: '3 to 5 characters long'.trigger: 'blur'}].grade: [{required: true.message: 'Please select grade'.trigger: 'change'}].subject: [{required: true.message: 'Please select grade'.trigger: 'change'}}]// Submit validation in methods
onSubmit() {
  this.$refs.form.validate((valid) = > {
    if (valid) {
      alert('submit! ');
    } else {
      console.log('error submit!! ');
      return false; }})}Copy the code

The above verification rules are simple. You can also customize more complex verification rules. For details, refer to the official document

conclusion

In this post, I hope you can get an idea of how to quickly create a front-end project and how to configure routes and forms. Of course, vUE also has many powerful functions, such as data management, asynchronous request interface encapsulation, filters, custom components, and so on. Although we do not need to be as deep as the professional front-end research, know why, try to understand some of the Vue development mechanism, to avoid the front-end page become a bottleneck in the development.

Hope you have a good harvest, thank you ~