vue添加axios,并且指定baseurl 两种方法

方法一(在入口文件main.js中实现)

1.import axios from ‘axios’
axios.defaults.baseURL=‘http://www.liulongbin.top:3005/’;
Vue.prototype.$http = axios
2. created(){
axios({
url:‘api/getlunbo’,
method: ‘get’,
})
.then(response =>{
console.log(response.status)
console.log(response.data.message)
if (response.status==200) {
this.lunbotuList=response.data.message
}else{
Toast(‘轮播图加载失败’)
}
})
.catch((error) =>{
console.log(error)
})
}

方法二 (通过全局的vue组件实现)

1.在main.js中全局引入axios
import axios from ‘axios’
Vue.prototype.$http = axios

2.添加一个Global.vue,内容如下:

3.在main.js中添加如下内容:
import global_ from ‘./Global.vue’
Vue.prototype.GLOBAL = global_;
axios.defaults.baseURL=global_.BASE_URL;

4.然后就能够正常的在各个模块中使用了。

后记:当然,很多全局变量都可以在Globa.vue中声明,并而且export出来。
在模块中使用的时候只需这样:
this.GLOBAL.BASE_URL即可。

created(){
let url = this.GLOBAL.BASE_URL+‘api/getlunbo’
axios({
url:url,
method: ‘get’,
})
.then(response =>{
console.log(response.status)
console.log(response.data.message)
if (response.status==200) {
this.lunbotuList=response.data.message
}else{
Toast(‘轮播图加载失败’)
}
})
.catch((error) =>{
console.log(error)
})
}

猜你喜欢

转载自blog.csdn.net/weixin_44345448/article/details/89923017