无法在vue单个文件组件

时间:2017-12-16 13:33:01

标签: javascript arrays vue.js

我有一个用单个文件组件制作的vue.js应用程序。我的数据中声明了一个空数组:

data: function () {
  return {
    teamKeys: []
  }
},

然后我在我的一个方法中将值推入其中:

fetchTeams (token) {
  var this_ = this
  var url = 'myapiserver.com/teams'
  this.axios.get(url, {
    params: {
      accessToken: token
    }
  })
    .then(function (response) {
      var teams = response.data.teams[0].teams
      teams.forEach(function (t) {
        this_.teamKeys.push(String(t.team_key))
      })
    })
    .catch(function (error) {
      console.log(error)
    })
},

(用实际的fetchTeams方法更新) 然后,在另一种方法中,我尝试使用forEach循环它。

fetchRosters (token) {
  var teamKeys = this.teamKeys
  teamKeys.forEach(function (key) {
    console.log(key)
    // do stuff
  })
}

这些方法在mount中一个接一个地调用:

mounted () {
    this.$nextTick(() => {
      var accessToken = this.$route.query.accessToken
      this.fetchTeams(accessToken)
      this.fetchRosters(accessToken)
    })
  }

forEach循环由于某种原因不起作用,似乎数组被视为空,因为forEach的内部永远不会被访问。另外,如果我在调用forEach之前执行此操作:

console.log(this.teamKeys)
console.log(JSON.stringify(this.teamKeys))

第二个输出为空[],第一个输出在控制台输出,如下所示:

Array(2)
0: "371.l.215756.t.1"
1: "371.l.621475.t.2"
length: 2
__ob__: Observer {value: Array(2), dep: Dep, vmCount: 0}
__proto__: Array

我确定我做的事情很愚蠢。我没有正确创建阵列吗?我甚至知道阵列是什么吗?

3 个答案:

答案 0 :(得分:1)

我认为你错过了第3段末尾的')'

答案 1 :(得分:1)

fetchTeams (token) {
  var this_ = this
  var url = 'myapiserver.com/teams'
  this.axios.get(url, {
    params: {
      accessToken: token
    }
  })
    .then(function (response) {
      var teams = response.data.teams[0].teams
      teams.forEach(function (t) {
        this_.teamKeys.push(String(t.team_key))
      })
      //this will run it
      this_.fetchRosters(token)
    })
    .catch(function (error) {
      console.log(error)
    })
},

答案 2 :(得分:0)

fetchTeams (token) {
  var this_ = this
  var url = 'myapiserver.com/teams'
  return this.axios.get(url, {
    params: {
      accessToken: token
    }
  })
}

mounted () {
  this.$nextTick(() => {
    var accessToken = this.$route.query.accessToken
    this
      .fetchTeams(accessToken)
      .then(function (response) {
        var teams = response.data.teams[0].teams
        teams.forEach(function (t) {
          this_.teamKeys.push(String(t.team_key))
        })
        this.fetchRosters(accessToken)    
      })
      .catch(function (error) {
        console.log(error)
      })
  })
}

或者:

fetchTeams (url, token) {
  return this.axios.get(url, {
    params: {
      accessToken: token
    }
  })
}

mounted () {
  this.$nextTick(async _ => {
    var accessToken = this.$route.query.accessToken
    var response = await this.fetchTeams('myapiserver.com/teams', accessToken)
    var teams = response.data.teams[0].teams
    teams.forEach(t => {
      this.teamKeys.push(String(t.team_key))
    })
    this.fetchRosters(accessToken)
  })
}