在Vue实例中

时间:2018-09-07 17:41:26

标签: vuejs2 this

是Vue的新手,在Vue实例中遇到 this 时遇到了麻烦。我的Vue数据对象是:

new Vue({
  el: "#app",
  data() {
    return {
      vm_instance_data: [],
      standings: [],
      currentTab: "",
      tabs: ["MLB", "NFL", "NBA"],
      isCompleted: false,
      gameDate: date.yesterday.substr(4, 2) + "." + date.yesterday.substr(6, 2),
      loading: false,
      errored: false
    };
  }

然后在我的方法对象中:

methods: {
    getSportsData: function(tab) {
      let url = "";
      this.currentTab = tab; // Set the currentTab

      //====== Get Standings From MySportsFeeds Site ======================================== //
      url = `https://api.mysportsfeeds.com/v1.2/pull/mlb/2018-regular/division_team_standings.json?teamstats=W,L,GB,Win %`;

      /* jshint ignore:start */
      async function getStandings() {
        console.log(this);
        this.standings = await mySportsFeeds.feedsData(url);
        console.log('standings is: ' + this.standings);
      }
      getStandings();
      /* jshint ignore:end */

      // ======= end Standings ================================================ //

      // ======== Let's check currentTab and make appropriate API call =============== //
      // ======== Use Axios Get to retrieve the baseball info ======================== //
      if (this.currentTab === "MLB") {
        this.loading = true;
        config.params = {
          team: "nyy,nym,bos,hou,lad,atl",
          force: true
        };

        axios
          .get(
            `https://api.mysportsfeeds.com/v1.2/pull/mlb/2018-regular/scoreboard.json?fordate=${
              date.yesterday
            }`,
            config
          )
          .then(response => {
            this.vm_instance_data = response.data.scoreboard.gameScore;
          })
          .catch(error => {
            console.log(error);
            this.errored = true;
          })
          .finally(() => (this.loading = false));
        // End ==== get.then ====== //

mySportsFeeds.js我只是想重构所有这些Axios调用:

module.exports = {
  /* jshint ignore:start */
  feedsData: async function(url) {
    url = encodeURI(url); // Format the URI

    return (await axios.get(url, config)).data.divisionteamstandings.division;
  }

  /* jshint ignore:end */
};

vue实例数据属性 this.standings 不能从axios调用获取数据。但是 this.vm_instance_data 工作正常。 getStandings()中的console.log(this)显示Windows对象?我很茫然。如果我在mySportsFeeds.js中使用console.log,则具有从API返回的对象数组。但是,当我在“主选项卡”下的“开发工具Vue”面板中查看时,排名是Array [0]。我真的可以在这里使用一些指导。预先感谢。

0 个答案:

没有答案