首页 > 移动平台 > 详细

Vue 3.x 中使用 Axios 请求远程Api接口数据

时间:2021-04-05 17:28:35      阅读:18      评论:0      收藏:0      [点我收藏+]

一、安装axios插件

npm install axios --save
//或者 yarn add axios
//或者 cnpm install axios --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)
      })
   }

Vue 3.x 中使用 Axios 请求远程Api接口数据

原文:https://www.cnblogs.com/qingheshiguang/p/14618614.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!