VUE项目学习(八):引用axios进行后端接口请求

VUE项目学习(八):引用axios进行后端接口请求

axios是一个基于 promise 的 HTTP 库,是vue中比较常用的后端接口请求方法。

演示效果为:

在这里插入图片描述

1、引入axios包

(1)执行命令,在vue项目中安装axios

npm install axios --save

安装完成结果图为:
在这里插入图片描述
(2)在main.js中添加以下代码,全局引入axios

import axios from 'axios'

Vue.prototype.$axios = axios

(3)在具体的vue文件中,直接使用this.$axios即可进行引用

2、vue中使用axios

(1)axios使用Get请求,实例如下:
请求的地址为:https://httpbin.org/get

		this.$axios
          .get('https://httpbin.org/get')
          .then(response => (this.value = response.data.url))
          .catch(error => (console.log(error)))

效果为:
在这里插入图片描述

(2)axios使用Post请求,实例如下:
请求的地址为:https://httpbin.org/post
请求参数为:{“username”:“666666@qq.com”,“password”:“666”}

		let param = {"username":"666666@qq.com","password":"666"}
        this.$axios
          .post('https://httpbin.org/post', param)
          .then(response => (this.value = response.data.data))
          .catch(error => (console.log(error)))

效果为:
在这里插入图片描述

3、完整代码为

<template>
  <div class="useaxios">
    <el-button type="primary" @click="sendGet()">请求Get接口</el-button>
    <el-button type="primary" @click="sendPost()">请求Post接口</el-button>
    <el-button type="warning" @click="reset()">重置结果</el-button>
    <div>
      <span>请求结果:</span>
      <span>{{value}}</span>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'useaxios',
    data() {
      return {
        value: ''
      }
    },
    methods: {
      sendGet() {
        this.$axios
          .get('https://httpbin.org/get')
          .then(response => (this.value = response.data.url))
          .catch(error => (console.log(error)))
      },
      sendPost() {
        let param = {"username":"666666@qq.com","password":"666"}
        this.$axios
          .post('https://httpbin.org/post', param)
          .then(response => (this.value = response.data.data))
          .catch(error => (console.log(error)))
      },
      reset() {
        this.value = ''
      }
    }
  }
</script>

<style>
  .useaxios {
    text-align: left;
  }
</style>

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值