位置:首页 > web前端 > vue

vue3.x利用Axios请求远程Api接口获取数据

dearweb 发布:2021-08-09 00:42:41阅读:

如果你是前端,,这几年也在不停的学习,相信对axios组件库并不陌生,这个大大提高了我们工作中的效率,很好的结局了之前ajax中存在的各种问题,下面我们一起走进axios的世界吧。

axios的安装

使用 npm:
$ npm 安装 axios
    
使用 bower:
$ bower 安装 axios
    
使用cdn:
< script  src = "https://unpkg.com/axios/dist/axios.min.js" > </ script >

除了以上安装方法,还可以使用cnpm以及yarn进行安装。

axios在vue中基本使用方法

<template>
  <div class="Axios">
    <button @click="getData">Axios获取数据</button>
  </div>
</template>
<script>
import axios from "axios";
export default {
  name: "Axios",
  created() {
    console.log(this.Axios);
  },
  methods: {
    getData() {
      console.log("获取数据");
      let getUrl = "http://www.baidu.com/s?wd=wuhan"; // 请求接口地址
      axios
        .get(getUrl)
        .then(
          // 请求成功的回调
          response => {
            console.log(response);
          }
        )
        .catch((error) => {
          // 处理错误
          console.log(error);
        });
    }
  }
};
</script>
<style lang='less' scoped>
</style>

axios在vue中全局使用

首先在main.js入口文件中做简单修改

import { createApp } from 'vue'
import App from './App.vue'
// 全局引入axios
import axios from 'axios'

const app = createApp(App)
// 挂载之前加入axios
app.config.globalProperties.Axios = axios
app.mount("#app")

在组件中使用方法

<template>
  <div>
    <button @click="getData">Axios获取数据</button>
  </div>
</template>
<script>
export default {
  name: "Axios",
  created() {
   },
  methods: {
    getData() {
      console.log("获取数据");
      let getUrl = "http://www.baidu.com/s?wd=wuhan"; // 请求接口地址
      this.Axios
        .get(getUrl)
        .then(
          // 请求成功的回调
          response => {
            console.log(response);
          }
        )
        .catch((error) => {
          // 处理错误
          console.log(error);
        });
    }
  }
};
</script>
<style scoped>
</style>

以上就是关于axios在vue3.x中基本使用以及全局挂载使用的方法,希望可以帮助到你喔!加油!

24人点赞 返回栏目 提问 分享一波

小礼物走一波,支持作者

还没有人赞赏,支持一波吧

留言(问题紧急可添加微信 xxl18963067593) 评论仅代表网友个人 留言列表

暂无留言,快来抢沙发吧!

本刊热文
网友在读
手机扫码查看 手机扫码查看