【问题标题】:Function within component throwing an error message组件内的函数抛出错误消息
【发布时间】:2021-12-29 17:44:14
【问题描述】:

我有一个在方法部分定义了两个函数的组件。每个都对一些 JSON 数据进行 API 调用。

第二个函数依赖于已经运行的第一个函数(我需要第一个函数的数据来通知第二个函数)。我的HTML 调用函数一并渲染它。在新呈现的内容中有一个 v-on:click 调用,它调用第二个函数,并将一个从第一个函数创建的值传递给它。

代码如下:

HTML

<div v-for="team in hockeyDataList.teams" :key="team.id">

              <!-- Loop through the teams array -->      
              <img :src="`https://www-league.nhlstatic.com/images/logos/teams-current-primary-dark/${team.id}.svg`" class="img-round team-logo"/>
              <h1>{{ team.name }}</h1>
              <div>Division: {{ team.division.name }} <br/> Conference: {{ team.conference.name }}</div>

              <h2>Roster</h2>
              <div class="player-cont">
                  <div v-on:click="getPlayerData(player)" v-for="player in team.roster.roster" :key="team.id + '-' + player.person.id" class="col" :id="player.person.id">
                      <h3>{{ player.person.fullName }}</h3>
                      <img :src="`https://cms.nhl.bamgrid.com/images/headshots/current/168x168/${player.person.id}.jpg`" class="img-round"/>
                      <div>
                      Number: {{ player.jerseyNumber }} | Position: {{ player.position.abbreviation }} 
                      </div>
                  </div>
              </div>
         
   </div>

VUE

data() {
      return {
        hockeyDataList: [],
        playerDataList: []
    },
    methods: {

    getHockeyData(teams) {      
        axios.get("https://statsapi.web.nhl.com/api/v1/teams/" + teams.id + "?expand=team.roster").then(response => (this.hockeyDataList = response.data));
      }
    },    
    getPlayerData(player) {
       axios.get("https://statsapi.web.nhl.com/api/v1/people/" + player.person.id + "/stats?stats=yearByYear").then(response => (this.playerDataList = response.data));
    }
  };

第二次调用时产生的错误是:

Property or method "getPlayerData" is not defined on the instance but referenced during render

我是 Vue 新手,我不确定这个错误是为了让我纠正什么。

【问题讨论】:

  • 问题是错误的格式,不允许任何人轻松阅读代码。
  • 就是这样粘贴的。当然可以提供更有效的注释,奇怪的缩进很少会产生错误消息。
  • 我们都把代码贴在SO上,这需要一些努力。这不是缩进本身,而是它很难发现错误。

标签: javascript json vue.js


【解决方案1】:

您在 methods 块之外编写了 getPlayerData 方法,请将其移回。

    methods: {

getHockeyData(teams) {      
    axios.get("https://statsapi.web.nhl.com/api/v1/teams/" + teams.id + "?expand=team.roster").then(response => (this.hockeyDataList = response.data));
  },
getPlayerData(player) {
   axios.get("https://statsapi.web.nhl.com/api/v1/people/" + player.person.id + "/stats?stats=yearByYear").then(response => (this.playerDataList = response.data));
  }
},    

datamethods 也是 2 个独立的块,例如

data() {
return{};
},
methods:{
},
computed:{
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    相关资源
    最近更新 更多