在vue中如何使用axios发送请求

本文介绍如何在Vue项目中使用axios库进行HTTP请求。首先,需要通过命令下载并安装axios。接着,展示了使用axios进行GET和POST请求的方法,以及如何并发请求和配置对象。在实际应用中,通过Vue组件间通信,比如从search.vue获取用户输入,通过父组件传递给list.vue,list.vue监听变化并利用axios发送请求,获取的数据动态显示在页面上。

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

axios是一个基于promise的http库,可以发送get,post请求(axios对ajax的封装),
正由于Vue,React的出现,促使了axios轻量级库的出现

直接使用会报错,需要下载axios,
下载安装命令npm install --save axios

使用axios在vue中发送ajax请求

  • get方式
    // 访问github的search接口
      let url = `https://api.github.com/search/repositories?q=${this.queryName}`;
      axios.get(url).then(
        // 当请求成功时触发此函数,参数response即是接收到的数据
        response => { 
          // console.log(response.data.items);//直接获取数据跨域报错

          // 我们要取的接口中的数据在数组中,而数组外面又被对象包含着
          // 先定义一个变量转存一下数据对象
          let result = response.data;
          console.log(result);

          // 再用一个数组转存一下数组
          let array = result.items[0]; //去数组中第一条数据
          console.log(array);

          this.reqName = array.name;
          this.reqUrl = array.html_url;

        },
        // 如果接口有问题时触发此函数,进行处理
        err => {
          console.log("接口出错了" + err);
        
        }).catch(error => { //如果请求出错触发此函数,捕获错误信息
        console.log("请求过程出错了" + error);

      });
  • post方式
      axios.post('/user',{ 
        firstName:"AA",
        lastName:"aa"
      }).then(response=>{
        console.log(response);
      }).catch(function(error){
        console.log("请求出错了");
      });
  • 执行多个并发请求
function getUser(){
   return axios.get(url); //返回一个get请求
}
function postUser(){
   return axios.post(url,{a:1}); //返回一个post请求
}
axios.all([getUser(),postUser()]).then().catch(){};
}
  • 配置对象方式
      axios({
        methods:"post",
        url:"/user/abc",
        data:{
          username:"tom",
          address:"beijing"
        }
      });

完整示例如下:

<template>
  <div id="app">
    <!-- 没数据时显示loading,有数据时隐藏 -->
    <h2 v-show="!reqUrl">
      <img src="./assets/loading.gif">
      <span>loading......</span>
    </h2>

    <!-- 显示数据 -->
    <h3 v-show="reqUrl">
      this is <a href="reqUrl">{{reqName}}</a>
    </h3>
  </div>
</template>

<script>
  // 哪里需要axios,就在哪里引入它 
  import axios from 'axios';
  export default {
    name: 'App',
    data() {
      return {
        reqUrl: "",
        reqName: "",
        queryName: "vue"
      }
    },
    // 创建当前根组件时
    created() {
      // 访问github的search接口
      let url = `https://api.github.com/search/repositories?q=${this.queryName}`;

      // 使用前先下载axios,下载安装命令npm install --save axios
      // 1、get请求方式
      axios.get(url).then(
        // 当请求成功时触发此函数,参数response即是接收到的数据
        response => { 
          // console.log(response.data.items);//直接获取涉及跨域报错
          // 我们要取的接口中的数据在数组中,而数组外面又被对象包含着
          // 先定义一个变量转存一下数据对象
          let result = response.data;
          console.log(result);

          // 再用一个数组转存一下数组
          let array = result.items[0]; //去数组中第一条数据
          console.log(array);
          
          // 接收接口中数组中指定元素的值
          this.reqName = array.name;
          this.reqUrl = array.html_url;
        },
        // 如果接口有问题时触发此函数,进行处理
        err => {
          console.log("接口出错了" + err);   
        }).catch(error => { //如果请求出错触发此函数,捕获错误信息
          console.log("请求过程出错了" + error);
      });
    }
  }
</script>

<style>
  #app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
  }

  #app img {
    width: 50px;
    height: 50px;
    vertical-align: middle;
    margin-right: 20px;
  }
</style>

综合示例,在vue中使用axios发送ajax请求,去访问github的接口下的数据
父组件App.vue

<template>
  <div id="app">
    <!-- :set-search-name这样写,报错setsearchName is not function
    名称较长时中间加一个连字符- -->
    <search :setsearch-name="setsearchName"></search>
    <list :search-name="searchName"></list>
  </div>
</template>

<script>
  import search from "./components/search";
  import list from "./components/list";

  export default {
    name: 'App',
  
    data() {
      return {
        searchName:""
      }
    },
    // 注册子组件
    components: {
      search,
      list
    },
    methods:{
      // 谁调用此方法,就将传过来的参数变为这里 存的值
      setsearchName(iptValue){
          this.searchName = iptValue;
      }
    }
  }
</script>

<style>
  #app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
  }
</style>

子组件
搜索search.vue

<template>
  <div>
     <input type="text" v-model="inputSearchName"/>
     <button @click="search">search</button>
  </div>
</template>

<script>
export default {
  name: 'search',
  props: ['setsearchName'],
  data(){
    return {
      inputSearchName:''
    }
  },
  methods:{
    // 获取输入框中输入的值
    // 所有的事情都在点击搜索按钮后的
    search(){
      // trim() 方法用于删除字符串的头尾空格。它不会改变原始字符串。
      // 这里是考虑用户没有输入任何内容到input框内的情况
      let iptValue = this.inputSearchName.trim();
      
      // 如果没有任何输入
      if(!iptValue){
        return;
      }
      // 如果有数据传入(将用户输入的内容传过来,去发ajax请求)
      this.setsearchName(iptValue);

      // 每次输入后再将输入框的内容置空
      this.inputSearchName = "";
    }
  }  
}
</script>

子组件
数据列表list.vue

<template>
  <div>
    <h2 v-show="firstView">Please searching</h2>
    <h3 v-show="loading">
       <img src="../assets/load.gif" alt="" class="load_img">
       <span>loading......</span>
    </h3>
    <h2 v-show="errorMsg">{{errorMsg}}</h2>
    <br>

    <!-- 存放数据的外层容器 -->
    <div class="showData" v-show="users">
      <!-- 存放每一条数据的容器 -->
      <div v-for="user of users" :key="user.id">
        <a :href="user.html_url">
          <img :src="user.avatar_url" alt="">
        </a>
        <p>{{user.login}}</p>
      </div>
    </div>
  </div>
</template>

<script>
  // 引入axios
  import axios from 'axios';
  export default {
    // 这里name名字不写也可以
    name: 'list',
    // 接收从search传过来的参数
    props:['searchName'],
    data() {
      return {
        firstView: true,
        loading:false,
        errorMsg:null,
        users:null
      }
    },
    // watch去监听searchName的值,如果变化了则说明用户开始往input框输入内容
    watch:{
      searchName(){
        // 用户输入内容后,改变firstView和loading的状态
        this.firstView = false;
        this.loading = true; 

        // 拿到searchName的值后发送ajax请求
        let url = `https://api.github.com/search/users?q=${this.searchName}`;
        // get请求方式
        axios.get(url).then(
          response=>{
             console.log(response);
             // 得到所需的数据后,loading隐藏  
             this.loading = false; 

             //  定义变量去存data
             let result = response.data;

             // 将取出的数据都存到users数组中 
             this.users = result.items.map(item=>{
               return {
                 id:item.id,
                 html_url:item.html_url,
                 avatar_url:item.avatar_url,
                 login:item.login
                 }
             });
          },
          error=>{
             console.log("接口出错了"+error);
          }
        ).catch(err=>{
            console.log("请求出错了"+err);
        });
      }
    }  
  }
</script>


<style scoped>
   .load_img{
     width: 30px;
     height: 30px;
     vertical-align: middle;
     margin-right: 20px;
   }
   .showData {
     overflow: hidden;
   }
   .showData div{
     float:left;
     width: 100px;
     height: 100px;
     margin: 10px 5px;
     /* border: 1px solid lightgray; */
   }
   .showData img{
     width: 60px;
     height: 60px;
     border-radius: 100px;
   }
</style>

分析:
search.vue中,获取用户输入input框中的内容,将它作为参数,通过父组件代为传递后给list.vue中;
list接收到这个参数后,通过watch监听参数是否发生改变,发生变化(即用户有输入)时,将参数拼接到指定的url中,传给axios去发送ajax请求,使用数组去接收请求到的数据,根据页面元素的结构,遍历渠道的数据显示到指定页面元素中。因为图片是放在a标签中,点击图片可以链接到github指定的地址。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值