简体   繁体   English

访问嵌套的JSON以在Vue.JS组件中使用的正确方法是什么?

[英]What is the correct way to access nested JSON for use in Vue.JS components?

I have a component that uses axios to get data from a JSON file. 我有一个使用axios从JSON文件获取数据的组件。

  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: JSON文件如下所示:

  {
   "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. 我需要显示JSON的方式是通过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: 我只需要能够将axios调用更新为以下内容:

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}}. 我的问题是我无法将axios调用的末尾更新为{{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. 最后,我可以将方法放到每条路线上,但是只需将response.data的末尾更改为所需的年份,但这似乎与可重用性背道而驰,因此我认为在做一些愚蠢的事情之前,我会问比我更聪明的人。 :x :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>

First of all, are you defining the year prop: 首先,您是否要定义year道具:

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

...inside your vue component like this? ...像这样在您的Vue组件内部?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM