【问题标题】:Unable to access `get` method in vue-resource无法访问 vue-resource 中的“get”方法
【发布时间】:2018-01-03 04:19:52
【问题描述】:

我有一个很小的 ​​vue 应用程序,我想在其中使用 vue-resource 来请求 api 端点。

  1. 我已经通过 npm 安装了vue-resource
  2. 我已将 Vue.use(VueResource) 行添加到我的引导文件中
  3. 我已经像这样设置我的组件来调用.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


【解决方案1】:

方法不应该是箭头函数。如果使用箭头函数声明方法,this 将不会指向 vue 实例。

改用普通函数:

methods: {
  fetchPosts(){
    debugger;
    this.$http.get('my-url')
      .then(response => {
        console.log(response)
      })
  } 

可以看到警告here

【讨论】:

  • 英雄!谢谢,就是这样。不过接受答案还有 11 分钟!
  • 顺便说一句,为什么方法对象不指向 vue 实例?作为一个新手,想要尽可能使用箭头函数但需要在其他地方定义旧函数有点尴尬。我预见到其他开发人员可能会重构 function 调用的问题!
  • @dougajmcdonald 我无法完全理解你......当创建 vue 实例或本质上是 vue 实例扩展的新组件时,Vue 在内部使用 bindthis 绑定到 vue实例。但是bind 不能与箭头函数一起使用,this 将是其执行的上下文,即模块本身。
猜你喜欢
  • 2017-04-01
  • 1970-01-01
  • 2021-07-08
  • 2022-01-05
  • 1970-01-01
  • 2020-10-04
  • 2016-12-21
  • 2019-09-10
  • 2021-03-12
相关资源
最近更新 更多