1. 此功能的原因:
1. 當(dāng)接口地址需要改動(dòng)時(shí)与殃,需要修改代碼重新提交龙宏、重新打包东亦;
2. 當(dāng)項(xiàng)目不需要修改功能寝贡;只需要改變一下接口地址重斑,其它項(xiàng)目可以直接部署使用時(shí)兵睛;
2. 思路:
配置一個(gè)json文件,可以通過(guò)修改此文件達(dá)到改變接口地址的目的窥浪;
此時(shí)便需要在頁(yè)面入口處可以讀到此文件祖很;
3: 實(shí)施
3-1: 新建pathConfig.json文件
此文件由于是對(duì)外可以進(jìn)行修改的,因此不能進(jìn)行編譯漾脂,可放在static文件夾下假颇;
{
"currEnv": "", // 如果為空,則默認(rèn)使用內(nèi)部自定義的環(huán)境地址
"dev": {
"protocal": "https://", // 如果為空骨稿,則默認(rèn)使用瀏覽器地址的協(xié)議
"baseUrl": "192.168.xx.xx:8080/test",
},
"test": {
"protocal": "",
"baseUrl": "192.168.xx.xx:8080/test",
},
"product": {
"protocal": "http://",
"baseUrl": "192.168.xx.xx:8080/test",
}
}
3-2: 在plugins文件夾下配置pathConfig.js獲取pathConfig.json中的配置掛在到全局Vue.prototype上笨鸡;
import Vue from 'vue';
import axios from 'axios';
const protocolTmp = window.location.protocol;
const { host } = window.location;
async function getServerConfig() {
return new Promise(async (resolve, reject) => {
await axios.get(`${protocolTmp}//${host}/上下文/pathConfig.json`).then((result) => {
const { currEnv } = result.data;
let config = {};
if (currEnv) {
Vue.prototype.currEnv = currEnv;
config = result.data[currEnv];
Object.keys(config).forEach((key) => {
Vue.prototype[key] = config[key];
});
}
resolve();
}).catch((error) => {
console.log(error);
reject();
});
});
}
getServerConfig();
3-3: 在nuxt.config.js中配置pathConfig.js
plugins: [
'@/plugins/pathConfig'
],
3-4: 在plugins/axios.js中使用
import Vue from 'vue';
import axios from 'axios';
import path from '~/config';
const timeout = 200000;
const protocal = Vue.prototype.protocal ? Vue.prototype.protocal : `${window.location.protocol}//`;
const baseUrl = Vue.prototype.currEnv ? `${protocal}${Vue.prototype.baseUrl}` : path.baseUrl;
export const indexAxios = axios.create({
baseURL: baseUrl,
timeout
});
至此姜钳,打包后,修改pathConfig.json中的地址后形耗,刷新頁(yè)面就可以使用新的接口地址了哥桥。