• 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)
          })
       }
    
  • 相关阅读:
    <script>标签的加载解析执行
    百度地图API位置偏移的校准算法
    开源实时消息推送系统 MPush
    开源GIS软件 4
    Bootstrap 只读输入框
    javascript中的后退和刷新
    HTML中的文本框textarea标签
    Spring Boot 特性 —— SpringApplication
    SpringMVC使用POST方法传递数据,却出现Request method 'GET' not supported?
    springboot的登录拦截机制
  • 原文地址:https://www.cnblogs.com/qingheshiguang/p/14618614.html
Copyright © 2020-2023  润新知