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?

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 Just do {{ verse.join(' ') }} (demo).
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

1 Comment

The OP's code is shorthand for what you're proposing.
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.