Project preparation

1. Create a Vue project

Start the server

Open the small leather panel, provided by its URL and initial account password login panel. Open the database, delete its original legacy files, add the database on your own server, and import it. After the database is imported, enter the server folder, Shift+ right click to open the PowerShell window, and enter the command Node app.js to open the server.

Erection of scaffolding

Open DOS command window, global installation scaffolding, installation is Vue CLI v4.5.13.

npm install @vue/cli -g
Copy the code

Create a project

There are two ways to create a Vue project

  1. Start by creating a folder in which to create my Vue project, using the command to create
vue create myproject
Copy the code

Select Manually select features. In addition to some default options, PWA (Progressive Web application: Progressive Web App (PWA) Support) Support, Router, and CSS pre-processors. Then select Vue 2.x, because this project uses hash mode route, so it does not need history mode route; Select Less for CSS preprocessing, then select the Standard ESLint + Standard Config configuration, and then Enter.

2. Enter the DOS window and run the command to open the GUI, open the Vue project manager on the web page, and create a new project.

vue ui
Copy the code

Open the Vue project Manager and create a new project. The selection of configuration items is the same as when using the command, which will not be described here.

The installation element – the UI

If you are using commands to create projects

npm add element-ui
Copy the code

Or go to The Project Manager and click On Dependencies → Install Dependencies → Install dependencies → Search For Element-UI → Select the official Element-UI → Install dependencies.

Project start

Analyze the project structure

All code data is basically placed under the SRC directory. Create API project in SRC directory, mainly used to store some files about data request; Assets are CSS, fonts, and images files. Component stores the various component files under which different directories are created based on the project structure; Plugin directory for inserting files such as element.js; The Router stores various routes that need to be configured during development. Utils is where the utility files used during development are stored; A view is a bunch of view files.

The view of this project is mainly divided into login, main page and a welcome page.

Project start

Login interface

The login page mainly consists of two input fields, user name and password, and consists of a form form, using the form in Element-UI and the icon icon. Because both username and password have validation conditions, bind the rules attribute to the form to verify that its username and password are correct.

required: Specifies whether this parameter is mandatory

Message: prompt message when required is false

Trigger and ‘blur’ : Verifies conditions when out of focus

Use the tokens in the sessionStorage sessionStorage on the login page to verify the user name and password.

Reasons for selecting sessionStorage among localStorage, sessionStorage, and cookie:

LocalStorage: localStorage, as long as the user does not take the initiative to clear the data, the data will exist forever, so this project is not applicable;

SessionStorage: sessionStorage, sessionStorage data will not fail, only when the user closes the browser, the data will be automatically cleared, for this project, is very suitable.

Cookie: Cookie storage can also be used to store user name and password information, but it is carried each time in the HTTP header, sent to the server, when using cookies to store too much data will affect its performance.

SessionStorage was chosen for a variety of reasons.

In the API directory, axios.js is used to handle Ajax requests, carrying tokens in configuration in AXIos’s request interceptor.

// Request interceptor
axios.interceptors.request.use((config) = > {
  // This config contains tokens
  config.headers.Authorization = window.sessionStorage.getItem('token') | |' '
  return config
})
Copy the code

Configure the route for the login page in the index.js file in the router directory, and set the route guard

router.beforeEach(async (to, from, next) => {
  if(to.path ! = ='/login') {
    if (window.sessionStorage.getItem('token')) {
      next()
    } else {
      next('/login')}}else {
    next()
  }
})
Copy the code

If there is no login token value in the sessionStorage, the login page is automatically displayed.

Main interface Home

The Main interface layout is divided into three blocks: Header, Aside and Main, using the Container layout in Element-UI. The first step is to configure and import a route for Home in the router.

Header

The head is divided into left and right parts. The left part contains a logo picture and title text of the system. On the right is a button to exit the platform. When the store opens this button, the token value stored in sessionStorage will be cleared. When the user enters the Home page again, it will automatically jump to the login page, which can only be accessed after login.

Aside

Aside is the side navigation bar, using NavMenu navigation menu, according to the background side navigation interface, asynchronous request navigation content.

 // Request side navigation data
  async created() {
    const { data: res } = await this.$http('menus')
    this.menuList = res.data
  },
Copy the code

Because each level 1 navigation has a corresponding icon icon, an icon array is defined for ICONS, which is specially used to store the ICONS corresponding to the level 1 navigation. Finally, the loop is iterated again.

async getMenuList() {
      const { data: res } = await this.$http.get('menus')
      if (res.meta.status === 200) {
        this.menuList = res.data
        res.data.forEach(item= > {
          for (var j in this.iconlist) {
            if (item.id + ' ' === j) {
              item.icon = this.iconlist[j]
            }
          }
        });
      } else 
        this.$message.error(res.meta.msg)
      }
    }
Copy the code

Main

List of users

Create a new directory under the Components directory to house components related to user management.

Configure routes for the user list interface, and the routes for these subinterfaces are configured as the children route of the Home, and then import components to complete the configuration.

At the head of the user list is a Breadcrumb navigation, which will be reused later in the development, so we introduced Breadcrumb navigation as a component for later reuse.

Below the breadcrumb navigation is a Card. The contents of the Card are divided into upper and lower parts, above is a compound search box and a button for adding new users, and below is a Form and Pagination page. The data and pages in the Form are obtained through the interface provided in the background.

There are three buttons in the operation, including edit, delete, and buttons that can assign different roles to users.

To facilitate later maintenance, I introduced editing users and assigning roles as sub-components.

In Add User, when the “Add User” button is clicked, a DILOG pops up for adding a user, including username, password, email, and mobile phone number. After the user is added, it is necessary to verify whether the data of the user horizon is legitimate. After the verification is passed, it can send a request to the background to store the newly added data in the database.

You need to use regular expressions to verify the validity of email addresses and mobile phone numbers.

// Verify that the mailbox is valid
var checkemail = (rule, value, callback) = > {
  const regEmail = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/;
  if (regEmail.test(value)) {
    callback()
  } else {
    callback(new Error('Please enter the correct email address'))}};// Verify that the mobile number is valid
var checkmobile = (rule, value, callback) = > {
  const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
  if (regMobile.test(value)) {
    callback()
  } else {
    callback(new Error('Please enter the correct mobile phone number'))}};Copy the code

In edit user, to achieve such a function, when clicking the edit button of a user, a Dialog Dialog of edit user will pop up, and the user name, email address and mobile phone number will also be displayed in the form of the Dialog box. When the user does not modify the information, give the user a lift information; When the user confirms that the information has been remodified, a request is made to the background to save the user’s information and update the data in the list.

The need for communication between components in order to achieve the above functions, father and son, when click one user, the parent component to “tell the child components which a user, I clicked on what the user information such as user name is”, the child components through prop to receive data from the parent component, when a user changes after the completion of the subcomponents thrown by $emit an event, “Tell me it’s done and you can update the list data.”

In assigning roles, the Select selector is used. It is necessary to obtain the list of all roles and confirm which role is selected according to their unique ID value.

Rights management

The role list

In the role list, different users have different permission levels, and different levels have different tag colors. Use V-if and V-else to achieve this function.

Permissions list

In the Permissions list, when the Assign Permissions button is clicked, in the pop-up dialog box is a permissions tree that allows users to be assigned different permissions.

Commodity management

List of goods

In addition to the normal request for item data, there is an Add button in the item list. When we click the add button, we need to redirect to another page, so we need to configure a route for the add button. This route is also registered in Home, and then add a click event @click=”$router.push(‘/goods/add’)” to the add button.

The Add item has a Steps bar above it and a left Tabs below and to the left.

In the tabs TAB on the left, you need to use the rich text editor for the product content. Download it in project Manager, import it in main.js, and then use it directly.

//main.js
// Introduce a rich text editor
import VueQuillEditor from 'vue-quill-editor'
// Introduces styles for the rich text editor
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// Global register rich text editor
Vue.use(VueQuillEditor)


// use in pages
 <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
Copy the code
Classification of parameter

A Cascader cascade selector is above the classification parameter and a Table Table is below it

Classification of goods

Tree-table is used in the Form Form of the product category.

You can search for vue-table-with-tree-grid in project Manager and install it into your project, or you can use it

NPM install vue-table-with-tree-grid-s install vue- table-with-tree-grid-s install vue- table-with-tree-grid-s install vue- table-with-tree-grid-s install vue- table-with-tree-grid-s

// Introduce the table tree
import TreeTable from 'vue-table-with-tree-grid'
// Globally register components
Vue.component('tree-table', TreeTable)
Copy the code

The order management

The order list

Data requests for an order list are not very different from data requests for a user list.

Data statistics

The statistics is an Echarts graph, which also uses Lodash, so we need to download it first and use it

npm install echarts -S
npm install lodash -S
Copy the code

Or search for downloads in project Manager.

After downloading, you can use it in the page you need to use.

// add echarts.js
import * as echarts from 'echarts';
/ / introduce loadsh
import _ from 'lodash'
Copy the code

The specific example code is as follows:


<template>
    <el-card>
      <div id="main" style="width: 750px; height:450px;"></div>
    </el-card>
</template>
<script>
// add echarts.js
import * as echarts from 'echarts';
/ / introduce loadsh
import _ from 'lodash'

export default {
  data() {
    return {
      // The data to be merged
      options: {
        title: {
          text: 'User Origin'
        },
        tooltip: {
          trigger: 'axis'.axisPointer: {
            type: 'cross'.label: {
              backgroundColor: '#E9EEF3'}}},grid: {
          left: '3%'.right: '4%'.bottom: '3%'.containLabel: true
        },
        xAxis: [{boundaryGap: false}].yAxis: [{type: 'value'}]}}},// The page has been rendered
  async mounted() {
    // 2. Initialize the echarts instance based on the prepared DOM
    var myChart = echarts.init(document.getElementById('main'));
    const { data: res } = await this.$http.get('reports/type/1')
    if(res.meta.status ! = =200) {
      return this.$message.error('Failed to request line chart data')}// 3. Specify the configuration items and data for the chart
    const result = _.merge(res.data, this.options)
    // 4. Use the configuration items and data just specified to display the chart.
    myChart.setOption(result);
    // console.log(option);}};</script>
Copy the code