vue脚手架中axios的使用

vue脚手架项目中安装axios

在终端输入以下命令安装axios

npm install axios

然后在项目的main.js中引入axios,一般新建的项目即使安装了axios依赖也不会自己引入,这里需要手动引一下

import axios from 'axios'
//引入完成之后需要挂载到vue上
Vue.prototype.$http = axios

然后就可以在项目中使用axios来进行网络请求了

this.$http.get('10.127.0.1:8080/get').then((res)=>{
    	console.log(res);
	}).catch(function (error) {
    	console.log(error);
  	})
this.$http.post('10.127.0.1:8080/user',{
		userName:'',
		passWord:''
	}).then((res)=>{
    	console.log(res);
	}).catch(function (error) {
    	console.log(error);
  	})

使用很简单,讲讲配置,在main.js中定义一个总的请求ip和端口号,这样在写请求的时候只需要写路由,前面的ip和端口axios会自动加上去,

// 引入
import axios from 'axios'
// 导入挂载axios
Vue.prototype.$http = axios
// 配置请求根路径
axios.defaults.baseURL = 'http://10.127.0.1:8080/'
// 配置请求超时时间
axios.defaults.timeout = 5000 // 单位是毫秒

现在使用便捷

this.$http.get('/obtain').then((res)=>{
	console.log(res);
})

还有更便捷的

如果项目是成功失败都有返回,然后在返回数据的code储存成功与否的话,可以使用async await方式提升代码效率

async login(){
	// 因为请求只有成功,这里就不管失败,将返回值直接存起来,解构赋值给data,并且给data起个res的别名,
	const { data: res } = await this.$http.get('/obtain' )
	// 如果返回值告诉我们请求失败了,就直接return出去结束方法
	if (res.code== '200') {
	  return console.log('失败')
    }
    // 请求成功,将数据拿出来使用
    console.log(res)
}
Logo

前往低代码交流专区

更多推荐