首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Vue使用axios

Vue使用axios

作者头像
苦咖啡
发布2019-12-10 18:01:28
1.1K0
发布2019-12-10 18:01:28
举报
文章被收录于专栏:我的博客我的博客我的博客

使用axios访问API

一、按需引入 1、安装 yarn add axios

2、导入 import axios from ‘axios’

3、使用   mounted: function () {     // 按需引入     axios.get(‘https://api.coindesk.com/v1/bpi/currentprice.json’).then(response => {       console.log(‘按需引入’)       console.log(response.data)     }).catch(error => console.log(error))   },

二、全局引入 1、全局引入-结合Vueaxios 1.1安装 yarn add axios vue-axios

1.2入口文件导入 import VueAxios from ‘vue-axios’ import axios from ‘axios’

Vue.use(VueAxios, axios)

1.3使用   mounted: function () {

    // 全局使用vue-axios     this.axios.get(‘https://api.coindesk.com/v1/bpi/currentprice.json’).then(response => {       console.log(‘全局引入’)       console.log(response.data)     }).catch(error => console.log(error))   },

2、全局引入-使用原型属性(不推荐) 2.1安装 yarn add axios

2.2入口文件导入 import axios from ‘axios’

更改属性 Vue.prototype.$axios = axios

2.3使用 mounted: function () {     // 全局使用prototype     this.$axios.get(‘https://api.coindesk.com/v1/bpi/currentprice.json’).then(response => {       console.log(‘全局引入2’)       console.log(response.data)     }).catch(error => console.log(error))   },

3、全局引入-结合vuex 3.1安装 yarn add vuex

3.2入口文件引入 import Vuex from ‘vuex’ import axios from ‘axios’

Vue.use(Vuex) const store = new Vuex.Store({   state: {     num: 1   },   actions: {     // 封装一个 ajax 方法     test () {       axios({         method: ‘get’,         url: ‘https://localhost:8080/test.json’,         data: {}       }).catch(error => { console.log(‘错误提示’, error) })     }   } })

3.3使用    methods: {     submitForm: function () {       console.log(‘被点击’)       this.$store.dispatch(‘test’)     }   }

vuex插件手册 https://vuex.vuejs.org/zh/

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年12月7日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档