vue全局使用axios(个人笔记),入门常见错误

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请求都拿不到参数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值