Vue.js: как перебрать v-for в динамический массив - PullRequest
0 голосов
/ 08 декабря 2018

Я хочу отобразить несколько таблиц html инструментов (1 таблица = 1 категория инструмента / 1 tr = 1 инструмент).

data() {
    return {
      cats: '',
      tools: [],
    };
  },
  methods: {
    getToolCats() {
      var rez = getToolCats();
      rez.then(data => this.receiveCats(data) ) 
    },
    receiveCats(_cats){
      this.cats = _cats;
      _cats.forEach(cat => {
        getToolsByCat(cat.href).then(data => this.tools[cat.href] = data);
      });
      console.log(this.tools);
    },
  },
  mounted() {
    this.getToolCats();
  },

cats (т.е. категории) - это массив, заполненный вызовом API.Затем для каждого кота вызов API дает мне список инструментов этого кота, который я помещаю в массив инструментов (this.tools [cat.href] = data).

Вот код отображения:

<div v-for="cat in cats" :key="cat.href" class="tbox col-xs-12 col-sm-6">
    ....
    <table class="table table-hover">
        <tr v-for="tool in tools[cat.href]" :key="tool.href">
            <td>...</td>
        </tr>
    </table>
    ....
</div>

Если я использую одну переменную для хранения списка инструментов, все в порядке.Но хотя я не знаю, сколько у меня будет кошек, я не могу создать машину для каждой категории.

Я думаю, что проблема может быть там:

  • Использование массива в v-for с ключом, не определенным в смонтированном состоянии:

v-for = "инструмент в инструментах [cat.href]

Я буду признателен за любую помощь!

1 Ответ

0 голосов
/ 09 декабря 2018

Vue не может обнаружить динамическое добавление свойства в this.tools[cat.href] = data, но обнаружит изменение с this.$set или Vue.set в this.$set(this.tools, cat.href, data):

new Vue({
  el: '#app',
  data() {
    return {
      cats: [],
      tools: {}, // <-- make this an object (not an array)
    };
  },
  mounted() {
    this.getToolCats();
  },
  methods: {
    getToolCats() {
      // setTimeout to simulate delayed API calls...
      setTimeout(() => {
        this.cats = [
          { href: 'https://google.com' },
          { href: 'https://microsoft.com' },
          { href: 'https://apple.com' },
          { href: 'https://amazon.com' },
        ];
        this.cats.forEach((cat, i) => {
          setTimeout(() => {
            const data = { href: cat.href };
            this.$set(this.tools, cat.href, data); // <-- use this.$set for dynamic property addition
          }, i * 1000);
        })
      }, 1000);
    }
  }
})



  Loading...
  
    
      
        cat.href: {{cat.href}}
      
    
  
  tools: {{tools}}
...