This article will briefly share the following four points

  • How do I use Axios
  • How to Isolate configuration
  • How to simulate data
  • Share your own project framework

The main purpose of this paper is as follows

  • I hope I can help some people
  • Hope to get some advice
  • Here is a template framework using Vue

I’m just sharing what I find useful

Use AXIOS to request the interface

Axios is a Promise-based HTTP library that can be used in browsers and Node.js.

Install axios

npm install axios --save

Creating an AXIos instance (API /fetch. Js)

The default axios submission format is: Application/JSON can be converted into application/ X-www-form-urlencoded by setting the transformRequest attribute data => Qs.stringify (data) can be submitted as a normal form

import axios from 'axios'

const instance = axios.create({
  baseURL: 'apiBaseUrl'./ / API base_url
  timeout: 10000 // Request timeout
  // transformRequest: data => qs.stringify(data) //
})
// Request interceptor
instance.interceptors.request.use(
  e= > {
    e.params = e.params || {}
    e.headers = e.headers || {}
    / / set the default values
    return e
  },
  error => ({ status: 0.msg: error.message })
)
// Respone interceptor
instance.interceptors.response.use(
  response= > {
    const resp = response.data
    if (response.status === 200) {
      return resp
    }
    return resp
  },
  error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)
export default instance
Copy the code

Use wrapped fetch. Js

Create a new interface module in the API file and use the axios instance (API /fetch. Js) SRC/API/API_test.js

import request from '@/utils/fetch'

export function test(data) {
  return request({
    url: '/test'.method: 'post'.data: data
  })
}
Copy the code

When used, API/module.js can be introduced to call the method, and the API interface can be extended to the VUE instance by installing plug-ins, so that it can be more convenient to use in the project

Use the test module as an example to create a $API extension

src/api/index.js

import * as api_test from './test'

const apiObj = {
  api_test
}

const install = function(Vue) {
  if (install.installed) return
  install.installed = true
  Object.defineProperties(Vue.prototype, {
    $api: {
      get() {
        return apiObj
      }
    }
  })
}
export default {
  install
}
Copy the code

Install the $API extension in main.js:

import api from './api'
Vue.use(api)
Copy the code

Call this.$api.api_test.test().then(resp=>{… }).catch(()=>{… }) in the backend project, I rewrapped the dropdown box to receive Function as an argument, passing $api.api_test.test to save a lot of code.

Configuration reads for development and build environments

See a lot of them and share what I did in the project.

The current approach in the project is to create a different configuration for the environment in the Config folder, and then expose the configuration for that environment through index.js.

Directory structure and index.js

   config
        - _development.js
        - _production.js
        - _testing.js
Copy the code

config/index.js

module.exports = require('./_' + process.env.NODE_ENV).default
Copy the code

The directory structure in the actual project looks like this

On using mocks in projects

I felt uncomfortable when I saw a lot of projects using mock in the project, so I tried to make it independent. The function is not powerful, but it is enough for some small Demo. Simply simulating the data can make our Demo not worry about the API interface failure causing the vUE project to fail.

Here’s my solution

The use of express – mockjs

Express-mockjs is an API service middleware built by express+ Mock-Lite, which can be used to quickly help us build a local mock server

Related information:

  • express-mockjs
  • mock-lite

Install express-mockjs: NPM install express-mockjs –save-dev

Install Nodemon into the project to listen for mock code modifications

Install nodemon: NPM install nodemon –save-dev

Create mock-server/index.js to write the code to start the server

var path = require('path')
var express = require('express')
var mockjs = require('express-mockjs')

var app = express()

// Custom path prefix: '/ API '
var config = {
  port: 3000
}
// Find all interfaces in the API directory prefixed with/API
app.use('/api', mockjs(path.join(__dirname, 'api')))

// You can use --port to customize the boot port
var args = process.argv
for (let i = 0; i < args.length; i++) {
  if (args[i] === '--port' && i < args.length - 1 && args[i + 1] > 0) {
    config.port = args[i + 1]
    break}}console.log('mock-server[mockjs-lite]:http://localhost:' + config.port)
/ / the console. The log (' definition mockjs - lite: http://mockjs-lite.js.org/docs/examples.html)
app.listen(config.port)
Copy the code

Writing interface files

Create an API folder in the Mock-Server folder and write json/ JS JSON as documented in expess-MockJS

/**
 * Interface function description
 *
 * @url /api-access-path
 */

{
  "code": 0,
  "result|5": [
    {
      "uid|+1": 1,
      "name": "@name",
      "email": "@email"
    }
  ]
}
Copy the code

js

/** * home page links * * @url /home-links * * Here you can write a detailed description * of the parameters of the information. */

module.exports = {
  code: function() {
    // simulation error code, 1/10 probability of error code 1.
    return Math.random() < 0.1 ? 1 : 0
  },
  'list|5-10': [{ title: '@title'.link: '@url'}}]Copy the code

Running a mock server

Add the mock command to your project’s package.json and run: NPM run mock

"scripts": {
    //...
    "mock": "nodemon --watch mock-server node mock-server/index.js --port 6543"
  },
Copy the code

The directory structure

The development environment should work fine according to the above configuration, but how can I use my own small Demo after it is released? My approach is to generate JSON from the JS file and package it into the dist directory. See mock-server/build.js if you’re interested

Share your own project framework

Given that there is a template framework for more than one implementation (the UI uses element-UI, for good looks), there are separate instructions in docs in the repository for those interested.

Project address: github.com/yimogit/me-… Preview address: vue-admin.yimo. Link/Effect illustration: Before and after plastic surgery

conclusion

I feel the article is too much, what is not clear, but the important thing is the idea, the specific implementation can see the framework code ~

If there are any mistakes in this article, please point them out. If there is a better way to achieve, also hope to have a big guy to give advice.