在vue開發中遇到 加載json配置文件,而且這個配置文件不應被打包
這就需要在 public 目錄下 創建static目錄 。

在static目錄下 創建 config.json 文件 ,文件內容如下:
{ "apiUrl": "http://localhost/VueApi" }
讀取方法分兩種
一、在main.js 文件中直接讀取、調用
Vue.prototype.$http.get('static/config.json').then((res)=>{
//console.log('11111111');
var apiUrl= res.data.apiUrl;
console.log('apiUrl '+apiUrl);
axios.defaults.baseURL =apiUrl;//'http://localhost/VueApi';
}).catch(err => {
console.log("apiUrl "+err);
})
這樣 取到 apiUrl 后 直接賦給 axios.defaults.baseURL
二、在main.js讀取 並 在 任意 *.vue 頁面上調用
//獲取 外部config.json Vue.prototype.$http = axios; Vue.prototype.getConfig = function () { //this.$http.get('../static/config.json').then(res => { this.$http.get('static/config.json').then((res)=>{ Vue.prototype.apiUrl = res.data.apiUrl; console.log('11111111'); console.log(Vue.prototype.apiUrl); }).catch(err => { console.log(err); //console.log('22222'); }) }
調用方法
mounted() { //頁面 加載完畢 必須要有 this.
//console.log(this.getConfig());
this.getConfig()
},
