0
votes

I have a component that uses axios to get data from a JSON file.

  export default {
  name: 'TDsByYear',
  props: ['year'],
  data: function () {
    return {
      tds: [],
      games: [],
  }
  },
  methods: {
    async getTDs () {
      const response = await axios.get('../../static/td-data.json'); 
      this.tds = response.data.y2002; // How do I make y2002 settable using <TDsByYear year='y2002'></TDsByYear> so i can use y2003 etc...
      console.log(response.data.y2003)
    }
  },
  beforeMount(){
    this.getTDs()
  }
}

The JSON file looks like this:

  {
   "y2001": {
   "Game 8": [
      {
         "Name": "Joe"
         "Time": "80s"
      },
      {
         "Name": "Steve"
          "Time": "70s"
      }
      ],
   "Game 9": [
      {
         "Name": "Kate",
         "Time": "90s"
      },
      {
         "Name": "Mark"
          "Time": "100s"
      }
      ]
  },

   "y2002": {
      "Game 1": [
    {
         "Name": "Art",
         "Time": "120s"
      }

How I need to display the JSON is by Game.

y2001
  Game 8
   -Joe/Time
   -Steve/Time
  Game 9
   -Kate/Time
   -Mark/Time

y2002
  Game 1
   -Art/Time

Now, depending on what route I'm on, I'd like to access that year's data with props like this:

<TDsByYear year='y2003'></TDsByYear>

I just need to be able to update the axios call to something like this:

this.tds = response.data.{{year}};

Does any of this make sense? My issue is I can't update the end of the axios call to a dynamic prop like {{year}}. In the end I can just put the method on every route but just change the end of the response.data to the year needed, but this seemed to go against reusability so thought I would ask smarter people than myself before doing something stupid. :x

Here's my template:

<div class="TDsByYear-wrapper">
  <div v-for="(game,index) in year" class="game-wrapper">
      <div class="game-number">{{index}}</div>
    <div class="all-tds-wrapper">
      <div v-for="(index) in game" class="touchd-wrapper">
          {{index.Name}} / {{game[0].Time}}
    </div>
  </div>
</div>
1
Does this.tds = response.data[year]; not suit your needs?Stephen Thomas
Hey thanks but when I do that I get an error: Unhandled promise rejection ReferenceError: year is not defined at VueComponent._callee$ (TDsByYear.vue?973f:54) which is this line > this.tds = response.data[year];4ndy
I can access the data by doing: this.tds = response.data.y2002; Does this issue lie in how the JSON is structured? I need to be able to change the y2002 part within a template like <TDsByYear year='y2002'></TDsByYear>4ndy

1 Answers

0
votes

First of all, are you defining the year prop:

<TDsByYear year='y2003'></TDsByYear>

...inside your vue component like this?

exports = {
     props: ['year'],
     data() {
          return { . . . }
     }
.
.
.
}