我正在 Vue 应用程序和 CLI 中使用 axios 进行测试。我一直在使用 vue-resource,只需将其传递给 Vue.use (VueResource),我就可以在我的所有组件上访问它。如何使用 axios 实现这一点,所以我不必将它导入到组件中,而只需在 main.js 文件中定义一次?
原文由 FeRcHo 发布,翻译遵循 CC BY-SA 4.0 许可协议
_注意_:当 Vue 模块作为一个包安装并且不通过 CDN 使用时,如果从 CDN 导入 Vue,那么这种方法可以正常工作,那么我们有两个选项,首先是这里的答案,其次是在 main.js
中导入 Vue然后使用 Vue.prototype.{variable}=Axios
对于 VUE3,您需要添加以下代码:
句法:
app.config.globalProperties.{variable} = value;
例子:
app.config.globalProperties.$http = Axios; // Allow axios in all componenets this.$http.get
在你的 main.js 或 app.js
/**
* Importing libraries & componenets
*/
import { createApp } from 'vue';
import { createWebHistory, createRouter } from 'vue-router';
import Axios from 'axios';
/**
* Vue initialization
*/
const app = createApp({
components: {
Index
},
});
app.use(router);
app.config.globalProperties.$http = Axios; // Allow axios in all componenets this.$http.get
app.mount('#app');
您可以在组件中调用与 VUE2 相同的 GET 方法: this.$http.get('https://httpbin.org/get')
原文由 Mayank Dudakiya 发布,翻译遵循 CC BY-SA 4.0 许可协议
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答4.8k 阅读✓ 已解决
4 回答4.3k 阅读✓ 已解决
4 回答1.9k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
2 回答2.5k 阅读✓ 已解决
在 main.js 中,您只需将 Axios 分配给 $http。
main.js
通过修改 vue 原型,任何 vue 实例都可以在
$http
this
。 (例如this.$http.get('https://httpbin.org/get')
注意:
$http
现在是 axios 对象,所以你可以调用 axios 对象的任何方法,你都可以调用this.$http
。