1、//引入axios
import axios from ‘axios’
2、原型上绑定axios
Vue.prototype.$axios=axios
如下图
3、就可以直接调用了
getData() {
this.$axios
.get(“https://autumnfish.cn/api/joke/list?num=3”)
.then((res) => {
console.log(res);
});
},
4、局部使用的方式
5、vue中实际使用
a)第一种方法,请求方式get,无参数
getIdBook() {
let _this = this;
axios
.get("http://localhost:8081/api/v1/book/bookid/")
.then((resp) => {
console.log(resp.data);
_this.form = resp.data.data;
})
.catch((err) => {
this.$message({
type: "success",
message: "获取失败",
});
});
},
b)第二种方法,请求方式get,参数id
getIdBook(id) {
let _this = this;
axios
.get("http://localhost:8081/api/v1/book/bookid/" + id)
.then((resp) => {
console.log(resp.data);
_this.form = resp.data.data;
})
.catch((err) => {
this.$message({
type: "success",
message: "获取失败",
});
});
},
c)第三种方式,更简洁,官方推荐
getByName() {
this.$axios(
{
url:'http://localhost:9007/person/getByName',
method:"GET",
params:{
name:"小"
}
}
)
.then((res) => {
console.log(res);
})
},
d)第四种方式,只适合post,不适合get请求(报错)
getByName() {
var ceshi = new URLSearchParams();
ceshi.append('name', '小');
this.$axios.post('http://localhost:9007/person/getByName', ceshi)
.then(function (value) {
console.log(value);
})
.catch(function (reason) {
console.log(reason);
});
},
post成功图片
get报错图片
还有一种写法,官方写法,但是会报错(我也不懂为什么),解决方式就是上面那个
getByName() {
this.$axios.post('http://localhost:9007/person/getByName', {name:'小'})
.then(function (value) {
console.log(value);
})
.catch(function (reason) {
console.log(reason);
});
},
post,get都报错
6、新人常见错误
对象写法,把method写成methods,这个时候默认请求类型会是get,如果你打算发post请求,data的数据将会拿不到。还有一种常见的错误params写成param,无论是get请求还是post请求都拿不到参数