This article is written by Tuque community member Canruo starry sky, welcome to join tuque community, create wonderful free technical tutorials together, to force the development of programming industry.

Writing in the front

For a documentation, this article is not to teach you from zero to build a background management system, but it is based on a practical project, had set up a background management system framework, to teach you how to on the basis of the rapid development of their own background management system, can let the reader can under the condition of the master some basic knowledge, can also fit the vue background and development. Only contact with the project, in order to better understand the meaning of their knowledge, by analogy, the dead knowledge into live learning skills.

First run

# Clone project
git clone https://github.com/tuture-dev/vue-admin-template.git
# enter directory
cd vue-admin-template
# install dependencies
npm install --registry=https://registry.npm.taobao.org
# run
npm run dev
Copy the code

The source code for this article is available on Github. If you think we did a good job, please give ❤️ a thumbs up +Github repository + star ❤️

Added side navigation

  1. Create a new file. In SRC /views/, create an empty folder named test. In this folder, create a file named test.vue
  2. Adding a route. Open SRC /router/index.js, which is the background routing configuration file of the project. In the constantRoutes array, add routes in the following format:
{
  path: '/test'./ / url path
  component: Layout, // This is a globally unified layout file
  children: [{
    path: 'test'.// Secondary path
    name: 'test'.component: (a)= > import('@/views/test/test'), // Lazy load, here write the path of the added file
    meta: {
      title: 'test'.icon:'plane' // The configuration option configures the test name and icon}}},Copy the code

We can customize our ICONS and format files by downloading them from iconfont and placing them in the SRC/ICONS/SVG directory

You can configure the second-level navigation as follows:

  {
    path: '/material'.component: Layout,
    redirect: '/material/upload'.meta: {
      title: 'Material Management'.// Meta information, the name of the level navigation
      icon: 'plane' // Meta information, navigation icon name
    },
    children: [{
        path: 'check-template'.name: 'check-template'.component: (a)= > import('@/views/material/check-template'),
        meta: {
          title: 'View template',}}, {path: 'logo'.name: 'logo'.component: (a)= > import('@/views/material/check-logo'),
        meta: {
          title: 'to check the logo',}}, {path: 'generate'.name: 'generate'.component: (a)= > import('@/views/material/generate'),
        meta: {
          title: 'Generate footage',}}, {path: 'check'.name: 'check'.component: (a)= > import('@/views/material/check'),
        meta: {
          title: 'View footage',}},]},Copy the code

Once this configuration is complete, the framework automatically generates side and side navigation entries based on the routing configuration file. All we need to do is write vUE components and populate the framework according to the business requirements.

Use the Element UI component

Element UI provides a number of reusable components that can be used for a general background application. If the personalized demand is not high, we can be a “copy and paste” engineer, also known as “CV” engineer, rapid development.

For each component, there are examples of effects and code in the documentation. Just select the component you want, paste the code into our code file, and modify it slightly.

Network request

When the framework is completed, the front-end programmer’s main job is to initiate requests and render data. Now let’s go through the whole process.

Basic configuration

  1. Configure the proxy.

Because of cross-domain resource requests, all network requests that interact with the backend during development are brokered by Node.js underneath. The related documents

Open the vue.config.js file in the root directory

// Proxy all network requests beginning with '/admin'
proxy: {
  '/admin': {
    target: `http://localhost:8886/`.// Background service address
    changeOrigin: true.pathRewrite: {}}}Copy the code
  1. The configuration address

Production and development environments usually have different service addresses. Edit the.env.development and.env.production files and modify the VUE_APP_BASE_API configuration items in them

Take the development environment as an example:

VUE_APP_BASE_API = '/admin'
Copy the code
  1. Configuring interceptors

Open SRC /utils/request.js, which encapsulates an AXIos request object on which network requests in the system are processed. We can do some commonality work before the network request is sent and after receiving the reply from the server. For example, check whether the request is normal according to the status code of the server and provide corresponding prompt if the request is abnormal.

service.interceptors.response.use(
  response= > {
    const res = response.data
    // If the status code of the server is not 200, the request is abnormal and an error message is displayed.
    if(res.code ! = =200) {
      Message({
        message: res.msg || 'Error check your token or method'.type: 'error'.duration: 2 * 1000
      })
      return Promise.reject(new Error(res.msg || 'Error'))}else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error'.duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)
Copy the code
  1. Mount the request object

SRC /main.js first imports the network request object and mount it to the Vue global object so that it can be referenced directly in each component without further import.

import request from '@/utils/request'
Vue.prototype.req = request
Copy the code

Request and Render

  1. Build a simple Node service

For tutorial instruction only

let http = require('http');
let querystring = require('querystring');
let my_result = [{
    date: '2016-05-02'.name: 'Wang Xiaohu'.address: Lane 1518, Jinshajiang Road, Putuo District, Shanghai
}, {
    date: '2016-05-04'.name: 'Wang Xiaohu'.address: Lane 1517, Jinshajiang Road, Putuo District, Shanghai
}, {
    date: '2016-05-01'.name: 'Wang Xiaohu'.address: Lane 1519, Jinshajiang Road, Putuo District, Shanghai
}, {
    date: '2016-05-03'.name: 'Wang Xiaohu'.address: Lane 1516, Jinshajiang Road, Putuo District, Shanghai
}]

let server = http.createServer((req, res) = > {
    let post = ' ';
    req.on('data'.function (chunk) {
        post += chunk;
    });

    req.on('end'.function () {
        res.writeHead(200, {
            'Content-Type': 'application/json; charset=utf-8'
        })
        post = querystring.parse(post);
        console.log('post-data:', post);
        if (post) {
            let result = {
                code: 200.// msg: "server error"
                data: my_result
            }
            res.end(JSON.stringify(result));
        } else {
            let result = {
                code: '0'.msg: 'No data received'
            }
            res.end(JSON.stringify(result)); }}); }); server.listen(8886)
// Run it from the command line nodeserver.js
Copy the code
  1. The initiating
this.req({
  url: "getInfo? id=6".// Write the url corresponding to different services here, and the framework will automatically concatenate with baseURL
  data: {},
  method: "GET"
}).then(
  res= > {
    // Request processing after success
    console.log("res :", res);
  },
  err => {
    // Request failure processing
    console.log("err :", err); });Copy the code

As a best practice, network requests should be uniformly separated into a single file and server data processed on each specific page. For example, create a file SRC/API /test.js to write all the network requests needed in the test component.

// src/api/test.js
import request from '@/utils/request'

export function getList(params) {
  return request({
    url: 'getTableData'.method: 'get',
    params
  })
}


Copy the code

Introduce request methods in component test.vue

import { getTableData } from "@/api/test.js"; ... mounted:function() {
// Network requests are processed uniformly
getTableData().then(res= > {
  console.log("api tableData :", res);
  this.tableData = res.data;
},err=>{
  console.log("err :", err);
});
// Network requests are written directly to the file
this.req({
  url: "getTableData".data: {},
  method: "GET"
}).then(
  res= > {
    console.log("tableData :", res);
    this.tableData = res.data;
  },
  err => {
    console.log("err :", err); }); },Copy the code
  1. Network data flow

From the console, we can see that our request address is localhost:9528 and the address of the background service is localhost:8886. Why is it different? Let’s illustrate with a flow chart

Once the application is online, a similar solution (Nginx reverse proxy) can be used to solve the problem of CORS cross-domain resource access on the front end.

Hello Table

Now let’s write a tabular data display page in test.vue using the Table component provided by Element UI.

  1. Go to the Element UI Table component documentation and copy and paste the corresponding code. The framework has introduced the Element UI globally, so these components are ready to use. If it is another third-party component, we need to introduce it and then use it.
<template>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="date" label="Date" width="180"></el-table-column>
    <el-table-column prop="name" label="Name" width="180"></el-table-column>
    <el-table-column prop="address" label="Address"></el-table-column>
  </el-table>
</template>
Copy the code
  1. Request data when the component loads
  mounted: function() {
    this.req({
      url: "getTableData".data: {},
      method: "GET"
    }).then(
      res= > {
        console.log("tableData :", res);
        this.tableData = res.data  // Data rendering
      },
      err => {
        console.log("err :", err); // Handle business logic when an error occurs}); },Copy the code
  1. The actual effect

Normal service logic

When a service error occurs, an error message from the server is displayed. Popup this information is defined in the interceptor request.js file, which is uniform business logic error handling and can also be handled individually on each request.

Simple permission control

This permission control mode is static. Some complex dynamic permission management is not described here. The framework checks permissions with router.beforeEach route jump, where we can add configuration items. Enter the file SRC /permission.js. For example, only administrators can access the user management interface:

if (to.path === '/user/user') {
  let id = JSON.parse(localStorage.getItem('userInfo')).id
  console.log(id)
  if (id > 2) { //id>2 common users with no access rights
    next({ path: '/task' })
    window.alert('permission denied')}}Copy the code

conclusion

The most common operations in the future development have been introduced, which is more than enough for some small projects. No towering pine can grow in a flowerpot, and no swift horse can be trained in the courtyard. When the project is written more, a lot of things will naturally become transparent. A thousand Hamlets for a thousand readers, this is just a basic framework, in the process of development, we need to modify it, make it your own most comfortable framework.

This project is derived from: github.com/PanJiaChen/…

Want to learn more exciting practical skills tutorial? Come and visit the Tooquine community.

The source code for this article is available on Github. If you think it is well written, please give ❤️ a thumbs up +Github repository plus a star ❤️