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”:“[email protected]”,“password”:“666”}

		let param = {
    
    "username":"[email protected]","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":"[email protected]","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>

猜你喜欢

转载自blog.csdn.net/qq_26666947/article/details/112677757