【发布时间】:2020-04-03 06:44:23
【问题描述】:
如何在 Vue js 中全局分配 axios?
我正在尝试加载 Axios,以便可以在任何组件中访问它。
我正在尝试如下:
main.js
import axios from 'axios'
Vue.prototype.$axios = axios
home.js
buyers(data) {
return new Promise(function (resolve, reject) {
this.$axios.get(`/buyers?${data}`)
.then(response => {
resolve(response.data)
})
.catch(error => {
reject(error.response.data)
})
})
}
index.vue?6ced:203 Uncaught (in promise) TypeError: Cannot read 未定义的属性“$axios”
【问题讨论】:
-
最有可能的问题是您为您的
then回调使用了普通的function。输入新函数会更改this的值,因此它不会引用您的组件。如果您使用箭头函数,它应该没问题。如果您需要进一步的帮助,您需要发布周围的代码。请注意,错误消息说它无法读取 '$axiosof undefined'。它并不是说$axios是未定义的。 -
@skirtle。我编辑了代码
标签: vue.js vuejs2 vue-component