etayluz
etayluz

Reputation: 16436

Vue: How to do a nested loop and traverse a multidimensional array?

I have a multidimensional array called verses:

export default {
  name: "Example",
  data: () => ({
    verses: [['First', 'Verse'], ['Second', 'Verse']]
  })
}

I am trying to traverse the multidimensional verses array as such:

<p v-for="(verse, verse_index) in verses" :key="verse_index">
    <div v-for="(word, word_index) in verse" :key="word_index">
        {{ word }}
    </div>
</p>

I am getting this error:

[Vue warn]: Property or method "verse" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

How do I traverse a multidimensional array in Vue?

Upvotes: 0

Views: 176

Answers (3)

scar-2018
scar-2018

Reputation: 528

There is nothing wrong with using vue syntax in the above code.

The problem is because <div> is inside <p>

So this will work

<div v-for="(verse, verse_index) in verses" :key="verse_index">
  <div v-for="(word, word_index) in verse" :key="word_index">
    {{ word }}
  </div>
</div>

Upvotes: 1

tony19
tony19

Reputation: 138546

The <p> element cannot contain a <div>, so the browser hoists it outside, resulting in this template:

<p v-for="(verse, verse_index) in verses" :key="verse_index">
</p>
<div v-for="(word, word_index) in verse" :key="word_index">
  {{ word }}
</div>
<p></p>

Notice how the second v-for is outside the first v-for that defined verse.

If you really intended to insert the <div> inside <p> for some reason, you can workaround the issue by wrapping the <div> in a <template> to prevent the browser from parsing it:

<p v-for="(verse, verse_index) in verses" :key="verse_index">
  <template> 👈
    <div v-for="(word, word_index) in verse" :key="word_index">
        {{ word }}
    </div>
  </template>
</p>

demo

Upvotes: 1

Anup
Anup

Reputation: 629

Not sure if you are passing the data value correctly, but I have changed that a bit and its working fine for me .

   data:  () => {
    return {
      verses: [['First', 'Verse'], ['Second', 'Verse']]
    }
   }

And one suggestion. Its not recommended to use div tag inside a p tag

Upvotes: 1

Related Questions