【问题标题】:What is the correct way to access nested JSON for use in Vue.JS components?访问嵌套 JSON 以在 Vue.JS 组件中使用的正确方法是什么?
【发布时间】:2018-12-05 14:50:58
【问题描述】:

我有一个使用 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()
  }
}

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"
      }

我需要按游戏显示 JSON。

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

y2002
  Game 1
   -Art/Time

现在,根据我所走的路线,我想使用以下道具访问当年的数据:

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

我只需要能够将 axios 调用更新为以下内容:

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

这些有意义吗?我的问题是我无法将 axios 调用的结尾更新为像 {{year}} 这样的动态道具。最后,我可以将方法放在每条路线上,但只需将 response.data 的结尾更改为所需的年份,但这似乎不利于可重用性,所以我想在做一些愚蠢的事情之前先问问比我更聪明的人。 :x

这是我的模板:

<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>

【问题讨论】:

  • this.tds = response.data[year]; 不符合您的需求吗?
  • 嘿,谢谢,但是当我这样做时,我得到一个错误:未处理的承诺拒绝 ReferenceError: year is not defined at VueComponent._callee$ (TDsByYear.vue?973f:54) 这是这一行> this。 tds = response.data[年份];
  • 我可以通过以下方式访问数据:this.tds = response.data.y2002;这个问题是否在于 JSON 的结构?我需要能够在 之类的模板中更改 y2002 部分

标签: javascript json vue.js axios


【解决方案1】:

首先,你是否定义了year 属性:

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

...像这样在你的 vue 组件中?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    相关资源
    最近更新 更多