需求:
接口域名是從外部 .json 文件里獲取的。
思路:
在開始加載項目前 進行接口域名獲取,然后重置 接口域名的配置項。
實現:
1、config/index.js 文件 進行基礎配置
import axios from 'axios' const config = { requestUrl: 'http://qiniu.eightyin.cn/path.json', //動態域名所在地址 baseUrl: { dev: '/api/', pro: 'http://xxx.com/' // 接口域名,會被動態覆蓋 }, requestRemoteIp: () => { // 動態獲取 return new Promise((resolve, reject) => { axios.get(config.requestUrl).then(response => { config.baseUrl.pro = response.data.data.path; config.img.domain = config.baseUrl.pro; resolve() }, err => { reject() }); }); } } export default config
2、項目下main.js 文件 進行動態獲取
import config from '@/config/index.js' // 讀取接口域名 config.requestRemoteIp().finally(res => { /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' }) });
3、請求數據
const instance = axios.create({ baseURL: process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro })