在 Vue.Js + GitHub API (octokat.js) 中与 fetch() 斗争

Struggle with fetch() in Vue.Js + GitHub API (octokat.js)

(这里是初学者)

我正在尝试在 Vue.js 中创建一个应用程序,让我可以与 GitHub API 进行交互。我尝试使用 vue-github-api at first, but because of troubles working with pagination I switched to octokat.js.

我尝试使用 vue-github-api 文档中建议的相同模板,然后切换到 octokat。

为简洁起见,我将包括这个小示例:

<template>
  <div class="row">
    <div class="col-sm-3">
      <div class="panel panel-default">
        {{ user.name }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      userData: {},
      issuesList: {}
    }
  },
  mounted: function () {
    var Octokat = require('octokat')
    var octo = new Octokat({
      token: 'xxxxx'
    })

    octo.user.fetch(function (e, val) {
      this.userData = Object.assign({}, val)
      // or this.userData = val (not sure, which is correct)
    })
  },
  computed: {
    user: function () {
      if (this.userData) {
        return this.userData
      }
      return 'Uh-oh...'
    }
  }
}
</script>

<style></style>

我得到的是:

Uncaught TypeError: Cannot set property 'userData' of undefined

如果我这样做:

this.userData = octo.user.fetch()

然后如果我 console.log 它我得到这个:

[]

我似乎无法从 "fetch" 命令中获得所需的输出。

有没有人处理过类似的事情,或者您是否发现了明显的错误?

让我们看一下从 GitHub API:

中获取的代码
octo.user.fetch(function (e, val) {
  this.userData = Object.assign({}, val)
  // or this.userData = val (not sure, which is correct)
});

在您的回调函数中,您正试图分配给 this.userData,但它不起作用。

这里要看的是this指的是什么?

您正在将回调中的 this.userData 分配给 octo.user.fetch。结果 this 没有绑定到你的 Vue 实例——它会绑定到调用它的函数或者在你的情况下 undefined 因为转译器很可能添加了一个 'use-strict' pragma.

我该怎么办?

在 ES6 中我们有 arrow functions。箭头函数没有绑定 this,因此 this 仍然指的是您的 Vue 实例。

octo.user.fetch((e, val) => {
  this.userData = Object.assign({}, val)
});

进一步阅读