SoFunction
Updated on 2025-04-04

Summary of API interface management in vue project

The default vue project has been generated using vue-cli and installed axios, and is developed based on element-ui. The axiosconfig directory and the API directory are at the same level, mainly recording the configuration relatedness.

1. In the axiosconfig directory

import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import { Message, Loading } from 'element-ui'
// Response time = 5 * 1000
// Configure cookies//  = true
// Configure the request header['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
// Static resources.$static = ''

// Configure the interface address = ''
var loadingInstance
// POST parameter serialization (add request interceptor)(
 config => {
  loadingInstance = ({
   lock: true,
   text: 'The data is loading, please wait...',
   spinner: 'el-icon-loading',
   background: 'rgba(0, 0, 0, 0.7)'
  })
  if ( === 'post') {
    = ()
  }
  return config
 },
 err => {
  ()
  ('Request Error')
  return (err)
 }
)
// Return to status judgment (add response interceptor)(
 res => {
  if ( === 200) {
   ()
   return res
  } else {
   ()
   ()
  }
 },
 err => {
  ()
  ('The request failed, please try again later')
  return (err)
 }
)
// Send a requestexport function post (url, params) {
 return new Promise((resolve, reject) => {
  axios
   .post(url, params)
   .then(
    res => {
     resolve()
    },
    err => {
     reject()
    }
   )
   .catch(err => {
    reject()
   })
 })
}
export function get (url, params) {
 return new Promise((resolve, reject) => {
  axios
   .get(url, {
    params: params
   })
   .then(res => {
    resolve()
   })
   .catch(err => {
    reject()
   })
 })
}

2. In the API directory,


import { post } from '../axiosconfig/'
export default {
  login(params) {
    return post('/users/api/login', params)
  }
}

import { post } from '../axiosconfig/'
export default {
  regist(params) {
    return post('/users/api/regist', params)
  }
}

import user from './'
import active from './'
export default {
 api1,
 api2
}

3. Configuration

import api from './api/'
.$api = api

4. Use in components

Log in component
doLongin() {
 let params={}
 this.$api.(params).then(res => {
  (res)
 })
}
Register component
doRegist() {
 let params={}
 this.$api.(params).then(res => {
  (res)
 })
}