Преглед изворни кода

优化:配置文件封装为工具类

Martin пре 5 година
родитељ
комит
5b76064452
3 измењених фајлова са 37 додато и 4 уклоњено
  1. 8 0
      core/config/defaultConfig.js
  2. 25 0
      core/config/index.js
  3. 4 4
      utils/request/index.js

+ 8 - 0
core/config/defaultConfig.js

@@ -0,0 +1,8 @@
+// ** 本文件是config.js的默认数据 (考虑后期迭代 请勿修改本文件中的内容)
+// ** 如需修改配置请移步到根目录的config.js文件
+export default {
+  // 系统名称
+  name: "萤火商城2.0",
+  // 后端api地址
+  apiUrl: "./index.php?s=/api/",
+}

+ 25 - 0
core/config/index.js

@@ -0,0 +1,25 @@
+import config from '@/config.js'
+import defaultConfig from './defaultConfig.js'
+
+// 合并用户配置和默认配置
+const mergeConfig = Object.assign({}, defaultConfig, config)
+
+/**
+ * 配置文件工具类
+ * mix: 如需在项目中获取配置项, 请使用本工具类的方法, 不要直接import根目录的config.js
+ */
+export default {
+  // 获取全部配置
+  all() {
+    return mergeConfig
+  },
+
+  // 获取指定配置
+  get(key, def = undefined) {
+    if (mergeConfig.hasOwnProperty(key)) {
+      return mergeConfig[key]
+    }
+    console.error(`检测到不存在的配置项: ${key}`)
+    return def
+  }
+}

+ 4 - 4
utils/request/index.js

@@ -3,17 +3,17 @@
  */
 import store from '@/store'
 import request from './request'
-import config from '@/config'
+import Config from '@/core/config'
 
 // 后端api地址
-const baseURL = config.apiUrl
+const apiUrl = Config.get('apiUrl')
 
 // 可以new多个request来支持多个域名请求
 const $http = new request({
   // 接口请求地址
-  baseUrl: baseURL,
+  baseUrl: apiUrl,
   // 服务器本地上传文件地址
-  fileUrl: baseURL,
+  fileUrl: apiUrl,
   // 服务器上传图片默认url
   defaultUploadUrl: 'upload/image',
   // 设置请求头(如果使用报错跨域问题,可能是content-type请求类型和后台那边设置的不一致)