zoukankan      html  css  js  c++  java
  • Vue 3.x 中使用 Axios 请求远程Api接口数据

    一、安装axios插件

    npm install axios --save
    //或者 yarn add axios
    //或者 cnpm install axios --save
    

    注:安装包的时候 后面的 --save,如果不加,只安装在当前项目,把代码发给别人,是运行不了的,所以安装工具类包等,尽量都加上 --save

    二、如何使用(github说明

    1、在需要使用的组件中引入 axios模块import axios from 'axios'

    2、使用 axios.get 或者 axios.post 请求数据

    <template>
      <div>
        <button @click="getData()">获取api数据</button>
      </div>
    </template>
    
    <script>
    //1、引入 axios 模块
    import axios from 'axios'
    export default {
      data() {
        return {
          msg: "主页"
        }
      },
      methods:{
       getData(){
          var api="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1";
          //2.使用axios 进行get请求
          axios.get(api).then((res)=>{
            //请求成功的回调函数
            console.log(res)
          }).catch((err)=>{
            //请求失败的回调函数
            console.log(err)
          })
       }
    
      }
    };
    </script>
    

    三、全局配置 axios

    1、在 main.js中全局配置

    import { createApp } from "vue";
    import App from "./App.vue";
    import router from "./router";
    import store from "./store";
    import Axios from 'axios';//引入axios
    
    var app=createApp(App)
    app.config.globalProperties.Axios=Axios //全局配置axios
    
    app.use(store).use(router).mount("#app");
    

    小心得:自己写的属性,如果有很多地方使用,也可以使用全局绑定,比如我们写了一个 storage.js 模块,如果大量地方使用,我们就可以全局注册,
    方式一样,也是先在 main.js 中引入,如何使用 app.config.globalProperties.Storage=Storage ,然后在需要用到的地方使用 this.Storage就可以调用了

    2、使用的时候直接使用 this.Axios.get 或者 this.Axios.post 请求接口

     getData(){
          var api="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1";
          //2.使用axios 进行get请求
          this.Axios.get(api).then((res)=>{
            //请求成功的回调函数
            console.log(res)
          }).catch((err)=>{
            //请求失败的回调函数
            console.log(err)
          })
       }
    
  • 相关阅读:
    pku 1061 青蛙的约会 扩展欧几里得
    莫比乌斯反演
    51Nod 1240 莫比乌斯函数
    51Nod 1284 2 3 5 7的倍数 容斥原理
    51Nod 1110 距离之和最小 V3 中位数 思维
    51Nod 1108 距离之和最小 V2 1096 距离之和最小 中位数性质
    HDU 2686 Matrix 多线程dp
    51Nod 1084 矩阵取数问题 V2 双线程DP 滚动数组优化
    HDU 1317XYZZY spfa+判断正环+链式前向星(感觉不对,但能A)
    设计模式(4)---单例模式
  • 原文地址:https://www.cnblogs.com/qingheshiguang/p/14618614.html
Copyright © 2011-2022 走看看