vue加载外部json配置⽂件在vue开发中遇到加载json配置⽂件,⽽且这个配置⽂件不应被打包
这就需要在 public ⽬录下创建static⽬录。
在static⽬录下创建 config.json ⽂件,⽂件内容如下:
{
"apiUrl": "localhost/VueApi"
}
读取⽅法分两种
⼀、在main.js ⽂件中直接读取、调⽤
Vue.prototype.$('static/config.json').then((res)=>{
//console.log('11111111');
var apiUrl= res.data.apiUrl;
console.log('apiUrl '+apiUrl);
axios.defaults.baseURL =apiUrl;//'localhost/VueApi';
}).catch(err => {
console.log("apiUrl "+err);
})
这样取到  apiUrl 后直接赋给  axios.defaults.baseURL
⼆、在main.js读取并在任意 *.vue 页⾯上调⽤
//获取外部config.json
Vue.prototype.$http = axios;
Config = function () {
//this.$('../static/config.json').then(res => {
this.$('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');
})
}
调⽤⽅法vue json字符串转数组
mounted() {  //页⾯加载完毕必须要有 this.
/
/console.Config());
},

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。