需要一個配置文件,能在項目打包(build)時不被打包,方便修改,同時項目刷新時讀取改配置。
實現方法如下:
1.在項目的static目錄下創建project.config.json文件(名稱隨意,建議帶上config關鍵字,易於辨識)
內容為json格式:
1 { 2 "serviceUrl": "http://localhost:30001/service/api/", 3 "baseUrl": "https://192.168.1.11/data/", 4 "accessToken": "pk.eyJ1Ijf1w", 5 "geoFenceRadius": 20, 6 "retrieveInterval": 5000 7 }
2.在main.js中讀取該配置
讀取到配置后放入 Vue.prototype.baseConfig中,(baseConfig名稱可自定義)
為了保證能在vue實例中配置隨時可用,把vue的創建放到了axios讀取配置的回調里面。
代碼如下:
1 /* eslint-disable no-new */ 2 axios.get('./static/project.config.json').then((result) => { 3 Vue.prototype.baseConfig = result.data 4 new Vue({ 5 el: '#app', 6 router, 7 components: {App}, 8 template: '<App/>' 9 }) 10 }).catch((error) => { 11 console.log('get baseConfig error...' + error) 12 })
注意:
讀取配置信息用到了axios,需先安裝並引入
1 // 命令行安裝 2 npm install axios -S 3 // main.js 引入 4 import axios from 'axios'
3.使用配置
a.組件中使用,因為baseCofig已放入Vue.prototype中,組件中不需要引入,直接使用this獲取
1 this.baseConfig.baseUrl
b. js文件中使用,需要先引入Vue,通過Vue.prototype獲取配置
1 import Vue from 'vue' 2 let basetConfig = Vue.prototype.baseConfig //注意該行應放在export里面,否則獲取不到值
4.build后可以在static目錄下看到添加的配置文件