首页 > 解决方案 > Vue 实例中的 this

问题描述

对 Vue 来说相当新,在 Vue 实例中遇到了麻烦我的 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 返回的对象数组。但是当我查看 Main Tab 下的 Dev Tools Vue 面板时,排名是 Array[0]。我真的可以在这里使用一些指导。提前致谢。

标签: vuejs2this

解决方案


推荐阅读