0

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?

tony19
  • 125,647
  • 18
  • 229
  • 307
etayluz
  • 15,920
  • 23
  • 106
  • 151

3 Answers3

1

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

Anup
  • 589
  • 4
  • 8
1

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

tony19
  • 125,647
  • 18
  • 229
  • 307
  • Is there a way to traverse over the words in the verse without any tag (div or otherwise)? I just want all the words to go into the p tag. How can that be achieved without the use of any tag? – etayluz May 26 '21 at 16:18
  • 1
    @etayluz Just do `{{ verse.join(' ') }}` ([demo](https://codepen.io/tony19/pen/yLMoYNL)). – tony19 May 26 '21 at 16:29
1

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>
scar-2018
  • 510
  • 2
  • 9