【发布时间】:2018-01-03 04:19:52
【问题描述】:
我有一个很小的 vue 应用程序,我想在其中使用 vue-resource 来请求 api 端点。
- 我已经通过 npm 安装了
vue-resource - 我已将
Vue.use(VueResource)行添加到我的引导文件中 - 我已经像这样设置我的组件来调用
.get方法
博客.vue
...
mounted () {
this.fetchPosts()
},
methods: {
fetchPosts: () => {
debugger;
this.$http.get('my-url')
.then(response => {
console.log(response)
})
}
}
...
我已经看到一些 github 问题和 SO 帖子涉及此类问题,但大多数似乎与我不认为的不正确配置有关(很高兴被证明是错误的) !)
我得到的具体控制台错误是:
Error in mounted hook: "TypeError: Cannot read property 'get' of undefined"
奇怪的是,如果你看到我的debugger 行,如果我在那个时候看到console.log this.$http.get:
function (url, options$$1) {
return this(assign(options$$1 || {}, {url: url, method: method$$1}));
}
如果我让代码运行然后尝试console.log,我会得到:
Cannot read property 'get' of undefined
因此,我认为这是某种 this 上下文问题,但据我所知,参考应该是正确的......不是吗?
【问题讨论】:
-
不要在方法上使用箭头语法,因为您当前丢失了正确的
this上下文 - 使用 ES6 对象简写fetchPosts() { //...etc } -
@BertEvans 可能现在我知道了答案,但当时调试器语句和
get方法的存在让我感到困惑
标签: vue.js vuejs2 vue-resource