Vue 3.x 中使用 Axios 请求远程Api接口数据 您所在的位置:网站首页 vue请求外部接口 Vue 3.x 中使用 Axios 请求远程Api接口数据

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

2023-08-14 17:16| 来源: 网络整理| 查看: 265

一、安装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 请求数据 获取api数据 //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) }) } } }; 三、全局配置 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) }) }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有