This is the use of the VUE and React versions of Ant Design. The underlying layers of the two frameworks, Vue and React, are not considered here.

Vue Ant Design project

This is a test platform project.

Since we are using a complete framework, we follow the Vue Ant Design flow.

Installation using YARN is recommended

# Install scaffolding
yarn global add @vue/cli

Initialize the project
vue create antd-demo

# Introduce Vue Ant Design
yarn add ant-design-vue
Copy the code

From there we’ll import it globally directly in the main.js file

// main.js
import Vue from 'vue'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/antd.less'

Vue.use(Antd)
Copy the code

Use axiOS to manipulate the interface. We can handle it according to the actual situation:

// request.js
import Vue from 'vue'
import notification from 'ant-design-vue/es/notification'
import JSONbig from 'json-bigint' // To handle big data, it is recommended that the big number back end become a string

// Create an auth Axios instance
const auth = axios.create({
  headers: {
    'Content-Type': 'application/json; charset=UTF-8'.'X-Requested-With': 'XMLHttpRequest'
  },
  baseURL: 'api'.// api base_url
  timeout: 10 * 60 * 1000.// Request timeout is 10 minutes
  transformResponse: [function (data) {
    return JSONbig.parse(data)
  }],
})

// Request interceptor
auth.interceptors.request.use(config= > {
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    config.headers[ 'Authorization' ] = 'JWT '+ token // Allow each request to carry a user-defined token. Change the token based on the actual situation
  }
  return config
}, err)

// Response interceptor
auth.interceptors.response.use(
  response= > {
    if (response.code === 10140) {
      loginTimeOut()
    } else {
      return response.data
    }
  }, 
  error => { // Error handling
    / / timeout
    if(error.response && error.response.status === 500){
      notice({
        title: 'The server is abnormal${error.response.statusText}`,},'notice'.'error'.5)
      return
    }
    // ...
    notice({
        title: `${error.response && error.response.data && error.response.data.msg}`,},'notice'.'error'.5)})Copy the code

So let’s consider managing interfaces:

# API directory
- api
  - basic_config
    - device.js
    - ...
  - index.js
Copy the code

Above is the directory for the basic management of the API, where the device.js and index.js entry files are rendered.

// device.js
import { auth } from '@/utils/request'

export function getDeviceList(params) {
  return auth({
    url: '/path/to/url'.method: 'get',
    params
  })
}

export default {
  getDeviceList
}
Copy the code

Next we mount the interface on the prototype:

// index.js
import bc_device from './basis_config/device'
// ...

const api = {
  bc_device
}

export default api

export const ApiPlugin = {}

ApiPlugin.install = function (Vue, options) {
  Vue.prototype.api = api // Mount the API on the prototype
}
Copy the code

After that, adjust the proxy address:

// vue.config.js

const HOST = '0.0.0.0';
const PORT = '9002';
const DEV_URL = 'http://10.***.**.***' // Test the environment
module.exports = {
  devServer: {
    host: HOST,
    port: PORT,
    https: false.hotOnly: false.proxy: { // Configure cross-domain
      '/api': {
        // The domain name of the cross-domain API to access
        target: `${DEV_URL}`.ws: true.changOrigin: true.// pathRewrite: {
        // '^/api': ''
        // }}}}// ...
};
Copy the code

With the above configuration and modifications done, we can move the bricks…

Take the BC_device interface as an example.

# Partial page directory
- views
  - basis_config
    - comp This is where private components are stored
    - device_manage.vue
Copy the code
<! -- device_manage.vue --> <template> <div class="device_manage"> <a-table :rowKey="row => row.id" :columns="columns" :dataSource="data" :pagination="false" :loading="loading" /> </div> </template> <script> export default { name: 'device_manage', data () {const columns = [{dataIndex: 'operation', title: 'operation'}, //...]  return { columns, data: [], loading: false, } }, mounted() { this.getList() }, methods: GetLists () {let vm = this vm. Loading = true const params = {} vm.api.bc_device.getDeviceList(params).then(res => { if(res.code === '00000') { vm.data = res.data || [] } else { Vm. $message. Warning (res. MSG | | 'failed to get equipment list! ') } }).finally(() => { vm.loading = false }) } } } </script>Copy the code

You can happily add things to your frame.

React Ant Design project

The React Ant Design project is an information configuration backend.

It was developed directly using Ant Design Pro.

The installation method here is implemented according to the official website:

Create an empty folder as the project directory and execute in it:
yarn create umi

# choose ` ant - design - pro `
Select the boilerplate type(Use arrow keys) ❯ Ant-design-pro-create project with an layout-only Ant-design-pro Boilerplate, use together with umi block. app - Create project with a simple boilerplate, support typescript. block - Create a umi block. library - Create a library with umi. plugin - Create a umi plugin.Copy the code

I use typescript for development, which I recommend.

We use integrated UMi-Request

// request.ts
/ * * * * more detailed request network request tool API documentation: https://github.com/umijs/umi-request * /
import { getStore, removeStore } from '@/utils/storage';

import { extend } from 'umi-request';

import { notification } from 'antd';

import { stringify } from 'querystring';

import { router } from 'umi';

/** * exception handler */
const errorHandler = (error: {
  response: Response;
  data: { code: number; message: string}; }) :Response= > {
  const { response, data } = error;
  if (response && response.status) {
    // const errorText = codeMessage[response.status] || response.statusText;
    const errorText = data ? data.message : 'Wrong! ';

    const { status } = response;

    notification.error({
      message: 'Request error -${status}`,
      description: errorText,
    });

    /** * 10000 IP change * 10001 token timeout */
    if (response.status === 401 && (data.code === 10000 || data.code === 10001)) {
      router.replace({
        pathname: '/user/login',
        search: stringify({
          redirect: window.location.href,
        }),
      });
      removeStore('token'); }}else if(! response) { notification.error({ description:'Your network is abnormal and you cannot connect to the server',
      message: 'Network exception'}); }return response;
};

/** * Configures the default parameter */ for the request
const request = extend({
  errorHandler, // Default error handling
  credentials: 'include'.// Whether cookies are included in the request by default
});

// Request interceptor
request.interceptors.request.use((url, options) = > {
  const token = getStore('token') | |' '; // Empty your tokens at 401
  if (token) {
    options.headers = {
      // Handle the tokens in the header
      'Content-Type': 'application/json',
      Accept: 'application/json',
      Authorization: ` * *${token}`}; }return{ url, options: { ... options }, }; }); request.interceptors.response.use(async (response: any) => response);

export default request;
Copy the code

Handling interface requests:

// A partial directory of the interface
- services
  - port.ts
  - ...
Copy the code
import request from '@/utils/request';

// Get the list of configuration ports
export async function getNginxPort(params: object) {
  return request('/path/to/url', {
    method: 'get',
    params,
  });
}
Copy the code

Before performing the API request operation, we configure the agent ~

// config/proxy.ts
/** * Proxy does not take effect in production environment, So there is no configuration of The production environment * The agent cannot take effect in The production environment * so there is no configuration of The production environment * For details, please see * https://pro.ant.design/docs/deploy */
export default {
  dev: {
    '/api/': {
      target: 'http://***.**.***.**',
      changeOrigin: true,
      pathRewrite: { A '^': ' '}},}};Copy the code

So let’s implement the list data request for port allocation:

// pages/port/index.tsx import React, { Component } from 'react'; import { PageHeaderWrapper } from '@ant-design/pro-layout'; import { Table, message, Tag, Row, Input, Button } from 'antd'; import { SearchOutlined, DeleteOutlined, PlusOutlined, InfoCircleOutlined, } from '@ant-design/icons'; import { getNginxPort, postNginxPortItem, deleteNginxPortItem } from '@/services/port'; import moment from 'moment'; const { confirm } = Modal; interface NginxPortProps {} interface NginxPortState { data: object[]; loading: boolean; current: number; pageSize: number; total: number; showSizeChanger: boolean; showQuickJumper: boolean; } class NginxPort extends Component<NginxPortProps, NginxPortState> { constructor(props: any) { super(props); this.state = { data: [], loading: false, current: 1, pageSize: 10, total: 0, showSizeChanger: ShowQuickJumper: true, // show whether the number of pages is jumped. search: "}; } componentDidMount() { this.getList(); } getList = () => { const rn = this; const { pageSize, current } = rn.state; rn.setState({ loading: true, }); getNginxPort({ page_size: pageSize, page: current }) .then((res: any) => { if (res.code === 200) { rn.setState({ data: res.data.lists || [], total: res.data.total || 0, }); } else {message. Warn (res) MSG | | 'failed to get the port list! '); } }) .finally(() => { rn.setState({ loading: false, }); }); }; Onchange = (pagination: any) => {this.setState({current: pagination. Current, pageSize: pagination.pageSize, }, this.getList, ); }; Render () {const columns = [{title: 'type ', dataIndex: 'port', key: 'port', width: 120,}, {title:' type ', dataIndex: const columns = [{title: 'port', key: 'port', width: 120,}, {title: 'type ', dataIndex: 'sercode', key: 'sercode',}, {title: 'GIT address ', dataIndex: 'GIT ', key: 'GIT ',}, {title: 'type', dataIndex: 'type', key: 'type', render: (type: any) => <Tag color="blue">{type}</Tag>, width: 120,}, {title: 'create time ', dataIndex: 'created_on', key: 'created_on', render: (text: number) => <span>{moment(text * 1000).format('YYYY-MM-DD')}</span>, width: 120, }, ]; const { data, loading, total, current, pageSize, showSizeChanger, showQuickJumper, showModal, } = this.state; return ( <PageHeaderWrapper title={false}> <Table scroll={{ x: 1200 }} dataSource={data} columns={columns} loading={loading} onChange={this.onchange} rowKey={(record: any) => record.id} pagination={{ total, current, pageSize, showTotal: (_total) => '{_total}', showSizeChanger, showQuickJumper,}} /> </PageHeaderWrapper>); } } export default NginxPort;Copy the code

Okay, you can code in silence.

The latter

Well ~

Add features based on the actual situation, such as charts showing what you want to implement: Echart, Bizchart… , etc.

I prefer to use React Ant Design to develop backend systems using Vue and React versions of Ant Design. Of course, it depends on the actual situation of the team and business. By the way, typescript works really well, and it’s 2020, so consider incorporating it into your project.

For more on this blog, please go tomy blogs