1. 程式人生 > 其它 >vue2.x搭建saas專案系列之七:API介面及常量、基礎資料統一維護

vue2.x搭建saas專案系列之七:API介面及常量、基礎資料統一維護

技術標籤:vue2.xvuesaas專案架構

此篇幅主要介紹、我們是如何做API介面及常量統一維護,如有不足和建議請留言,在此感謝,專案目前階段還處在少年,一直在迭代

相信小夥伴們都知道,在同一個專案中,相同的介面會在很多地方被用到,而且在多人開發時,也很難讓每個人在開發之前去了解隊友負責的模組,這就會導致相同的程式碼會出現在無數個地方

API

講api之前,先貼一段封裝的request.ts

import axios from 'axios';
import { removeCookie } from '@/utils/auth'
import { Message, MessageBox } from 'element-ui'
const service = axios.create({
  timeout: 5000,
  withCredentials: true              // send cookies when cross-domain requests
})
// 在傳送請求之前做些什麼
service.interceptors.request.use( (config: any) => {
  return config;
}, (err) => {
  // 對請求錯誤做些什麼
  return Promise.reject(err);
});
// 新增響應攔截器
service.interceptors.response.use((response: any) => {
  // Some example codes here:
  // code == 200: success
  // code == 201: Created
  // code == 401: Unauthorized
  // code == 403: Forbidden
  // code == 404: Not Found
  // code == 506: 未登入 或者失效
  const res = response.data
  if (res.code === 200) {
    return response.data
  } else if (res.code === 506) {
    MessageBox.confirm(
      '登入資訊已過期,請重新登入',
      {
        confirmButtonText: '重新登入',
        type: 'error',
        showClose: false,
        showCancelButton: false,
        closeOnClickModal: false,
      }
    ).then(() => {
      removeCookie()
      sessionStorage.clear()
      window.location.href = "/"
    })
  } else {
    Message({
      message: `${res.msg}` || '系統未知錯誤,請反饋給管理員',
      type: 'error',
      duration: 2000
    })
    return Promise.reject(new Error(res.msg || '系統未知錯誤,請反饋給管理員'))
  }
}, (error) => {
  Message({
    message: error.message,
    type: 'error',
    duration: 2000
  })
  return Promise.reject(error)
});
export default service

api目錄下會有多個如下資料夾,以及types.d.ts

使用封裝request的GET和POST請求

import request from '@/utils/request';

const DEMO_URL = '/rest/os/dashboard'

export const post = (data: any) => {   
  return request({
    url: `${DEMO_URL}/uuid`,
    method: 'post',
    data
  })
}

export const get = (id: number) => {   
  return request({
    url: `${DEMO_URL}/detail/${id}`,
    method: 'get'
  })
}


  

types.d.ts

export interface IResp {
  /** 響應 code */
  code?: 200;

  /** 響應資料 */
  data?: any;

  /** 訊息 */
  msg?: string;
}

模組中引用

import { get, post } from '@/api/demo'

常量、基礎資料

常量和基礎資料的統一維護,關係到了後期對於整個專案的把控,baseData、constant、images統一放在assets目錄下進行管理

baseData為專案中使用到的基礎資料,比如省市區等類似的資料

constant為全域性模組的常量,每個模組會有一個.ts檔案,.ts檔案會包含當前檔名對應的.vue檔案下所使用到的所有常量,包括

多條件搜尋彈窗元件中使用到的常量、更多運算元組、Tab陣列、Table元件使用到的表格欄位陣列、表格操作物件等等

images就不多解釋了

到此,API介面及常量、基礎資料統一維護-文章結束,原創不易,感謝瀏覽!