在我的所有组件中全局使用 axios vue [英] use axios globally in all my components vue

查看:35
本文介绍了在我的所有组件中全局使用 axios vue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Vue 应用程序和 CLI 中使用 axios 进行测试.我一直在使用 vue-resource,我可以通过简单地将它传递给 Vue.use (VueResource) 来在我的所有组件上访问它.我如何使用 axios 实现这一点,所以我不必将它导入到组件中,而只需在 main.js 文件中定义一次?

I am testing with axios within a Vue application and the CLI. I've been using vue-resource and I could access it on all my components by simply passing it to Vue.use (VueResource). How can I achieve this with axios, so I do not have to import it into a component, but simply define it once in the main.js file?

推荐答案

在 main.js 中,你可以将 Axios 分配给 $http.

In main.js you can just assign Axios to $http.

main.js

import Axios from 'axios'

Vue.prototype.$http = Axios;

通过修改vue原型,任何vue实例都可以在this上调用$http.(例如 this.$http.get('https://httpbin.org/get')

By modifying the vue prototype, any vue instance will have the ability to call $http on this. (e.g. this.$http.get('https://httpbin.org/get')

注意:$http现在是axios对象,所以任何可以在axios对象上调用的方法,都可以在this.$http上调用.

Note: $http is the axios object now, so any method you can call on axios object, you can call on this.$http.

这篇关于在我的所有组件中全局使用 axios vue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆