在Vue中使用axios

本文介绍了如何在Vue项目中安装并使用axios库,包括全局和局部引入的方式,以及在组件中调用axios进行数据交互的基本操作。

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

在vue中使用axios

  1. 安装

    npm install axios
    
  2. 引入

    全局引入:在 main.js 中引入 axios(也可以在单页面局部引入)

    import axios from "axios"
    Vue.prototype.$axios = axios//设置全局变量axios
    
  3. 在组件中使用

    <template>
      <div class="demo">
        <button @click="toGet">get</button>
        <button @click="toPost">post</button>
      </div>
    </template>
    
    <script>
    export default {
      name: "Demo",
      components: {},
      data() {
        return {};
      },
      methods: {
        toGet() {
          // this.$axios
          //   .get("http://152.136.148.31:7401/portal/gnvq/getCatList")
          //   .then(function (response) {
          //     console.log(response);
          //   })
          //   .catch(function (error) {
          //     console.log(error);
          //   });
          // 或通过向 axios 传递相关配置来创建请求
          this.$axios({
            method: "get",
            url: "http://152.136.148.31:7401/portal/gnvq/getCatList",
          })
            .then(function (response) {
              console.log(response);
            })
            .catch(function (error) {
              console.log(error);
            });
        },
        toPost() {
          this.$axios.post('http://152.136.148.31:7401/portal/teacher/query', "pageNumber=0&pageSize=2")
              .then(function (response) {
                  console.log(response);
              })
              .catch(function (error) {
                  console.log(error);
              });
          // 或通过向 axios 传递相关配置来创建请求
          // this.$axios({
          //   method: "post",
          //   url: "http://152.136.148.31:7401/portal/teacher/query",
          //   data: "pageNumber=0&pageSize=2",
          // })
          //   .then(function (response) {
          //     console.log(response);
          //   })
          //   .catch(function (error) {
          //     console.log(error);
          //   });
        },
      },
    };
    </script>
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值