[Vuejs]-Vue.js : How to iterate with v-for into a dynamic array

0👍

Vue can’t detect dynamic property addition in this.tools[cat.href] = data, but it would detect the change with this.$set or Vue.set in 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);
    }
  }
})
<script src="https://unpkg.com/vue@2.5.17"></script>

<div id="app">
  <div v-if="!cats || cats.length == 0">Loading...</div>
  <div v-for="cat in cats" :key="cat.href" v-else>
    <table>
      <tr v-for="tool in tools[cat.href]" :key="tool.href">
        <td>cat.href: {{cat.href}}</td>
      </tr>
    </table>
  </div>
  <pre>tools: {{tools}}</pre>
</div>
👤tony19

Leave a comment