VUE—axios的get/post方法(图文详情)

本文详细介绍了如何在VUE项目中利用axios库实现GET和POST请求的方法。首先展示了如何在methods中定义请求函数,包括get和post方法的使用,以及如何在created生命周期钩子中调用这些函数。同时,通过console.log展示了请求成功和失败时的回调函数处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

VUE—axios的get/post方法

下载引入axios

第一步:在methods写方法

methods: {
    getUrl () { //get方法
      axios.get('https://www.easy-mock.com/mock/5d41580a1a802c0d5e53dcc2/example/aa')
        .then((res) => {
          console.log(res.data)
        })
         // then是获取成功的回调函数
        .catch((err) => {
          console.log(err)
      })
      // catch是获取失败的回调函数,若地址错误console.log会出现404
    },
    postUrl () {  //post方法
      axios.post('https://www.easy-mock.com/mock/5d41580a1a802c0d5e53dcc2/example/bb')
        .then((res) => {
          console.log(res.data)
        })
        .catch((err) => {
          console.log(err)
        }) 
    },
    axiosFn () {  //不推荐
      axios({
        method: 'get',
        url: 'https://www.easy-mock.com/mock/5d41580a1a802c0d5e53dcc2/example/aa'
      })
        .then((res) => {
          console.log(res.data)
        })
        .catch((err) => {
          console.log(err)
        })
    }
  },

第二步:在created调用方法

 created () {
    this.getUrl()
    this.postUrl()
    this.axiosFn()
  }

console.log结果如下
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值