vue全局使用axios发ajax请求

首先,我们要通过 npm/Yarn 或一个 CDN 链接安装 axios。
axios单文件使用例子:请求发送到 https://api.coindesk.com/v1/bpi/currentprice.json。我们首先创建一个 data 里的属性以最终放置信息,然后将会在 mounted 生命周期钩子中获取数据并赋值过去:

new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => (this.info = response))
  }
})
<div id="app">
  {{ info }}
</div>

如果要多个文件使用axios发ajax请求,简单点就是每个文件引用一次,import axios from 'axios',但是太麻烦了。
所以介绍方便全局使用的解决方法:
1.结合 vue-axios使用

  1. axios 改写为 Vue 的原型属性
    3.结合 Vuex的action

1.结合 vue-axios使用
vue-axios是按照vue插件的方式写的。结合vue-axios,可以去使用vue.use方法。
在主入口文件main.js中引用
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios);

之后就可以全局使用this.axios了,在组件文件中的methods里去使用了,下面三种写法都可以

Vue.axios.get(api).then((response) => {
  console.log(response.data)
})
 
this.axios.get(api).then((response) => {
  console.log(response.data)
})
 
this.$http.get(api).then((response) => {
  console.log(response.data)
})

2.axios 改写为 Vue 的原型属性
首先在主入口文件main.js中引用,之后挂在vue的原型链上
import axios from 'axios'
Vue.prototype.$http= axios
在组件中使用

this.$http.get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => (this.info = response))
  }
})

3.结合 Vuex的action
在vuex的仓库文件store.js中引用,使用action添加方法

import Vue from 'Vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
const store = new Vuex.Store({
  // 定义状态
  state: {
    user: {
      name: 'Tom'
    }
  },
  actions: {
    // 封装一个 ajax 方法
    login (context) {
      axios({
        method: 'post',
        url: '/login',
        data: context.state.user
      })
    }
  }
})

export default store

在组件中发送请求的时候,需要使用 this.$store.dispatch

methods: {
  submitForm () {
    this.$store.dispatch('login')
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 文档: https://www.kancloud.cn/yunye/axios/234845官网: https:/...
    谢大见阅读 54,277评论 2 44
  • ## 框架和库的区别?> 框架(framework):一套完整的软件设计架构和**解决方案**。> > 库(lib...
    Rui_bdad阅读 8,209评论 1 4
  • 在vue项目开发中,我们使用axios进行ajax请求,很多人一开始使用axios的方式,会当成vue-resou...
    ozil_oo阅读 4,750评论 0 2
  • vue-cli搭建项目 确保安装了node与npm 再目标文件夹下打开终端 执行cnpm i vue-cli -g...
    Akiko_秋子阅读 8,532评论 1 22
  • 1、active-class是哪个组件的属性?嵌套路由怎么定义?答:vue-router模块的router-lin...
    jane819阅读 5,728评论 0 15

友情链接更多精彩内容