Skip to content
Advertisement

Watching parent with prop doesn’t update during for loop

I have 2 components – <my-component> and <grand-child-comp>.

In my root there is a multidimensional object and my component watches it with prop.

<div id="app">
   <my-component v-bind:account-types='accountTypes'>
   </my-component>
</div>

In Vue debugger, I can see that my-component is getting and watching accountTypes object successfully. However, when trying to use it in my-component's template, it doesn’t work.

Vue.component('my-component', {
    template: `
       <div>
          <grand-child-comp v-for="(account, index) in accountTypes" :key="index"></grand-child-comp>
       </div>
    `
}

Lastly, accountTypes object looks like:

{ 1 : [ 'a', 'b', 'c' ], 2: ['e', 'a', 'm'] }

Advertisement

Answer

The problem is you’re doing the v-for and passing a property at the same time on the same element. You need to nest them so that the element the v-for is on wraps the <grand-child-comp>. The documentation recommends a template for this.

<template v-for="(account, index) in accountTypes">
  <grand-child-comp  :key="index"></grand-child-comp>
</template>

UPDATE: Based on what you said in your comments, what it sound like you really need is two nested for loops.

<!-- loop over account types -->
<div v-for="(accountId, values) in accountTypes">
  <h3>{{ accountId }}</h3>
  <!-- then loop over each individual value -->
  <ul v-for="value in values">{{ value }}</ul>
</div>

Your usage of components wasn’t necessary. Components are only needed if you plan to use something in multiple places around your app. Just because the for loop is repeating the same elements multiple times doesn’t mean you actually need a component there; The template inside the for loop would be enough.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement