5

This is my vue instance:

var vue = new Vue({
  el: '#vue-wrapper',
  data: {
    items: [],
}})

This is a v-for loop in my index.html.eex

<div v-for="item in items[0].subItems">{{item.name}}</div>

This is the script where I populate items, on document ready, with data passed during rendering from my Phoenix server.

<script type="text/javascript">
      jQuery(document).ready(function() {
      //Assign server-side parameters
      vue.items = <%= raw(@items) %>;
      console.log(vue.items);
    });
</script>

The log function shows the proper list of items that i want. Problem is that I can't access them in the v-for loop, I'm getting:

vue.min.js:6 TypeError: Cannot read property 'subItems' of undefined

I can't access the first element, like items are still not populated. How can I achieve this? I'm forced to initialize it in the index.html.eex file because I need the eex syntax to retrieve data passed from the server.

2
  • 1
    It's likely your Vue is created before the data is available, which results in the undefined. Commented Feb 16, 2018 at 14:38
  • 1
    Why are you loading your data via jQuery, instead of inside Vue (such as inside a mounted() hook)? Commented Feb 16, 2018 at 15:15

3 Answers 3

10
var vue = new Vue({
  el: '#vue-wrapper',
  data: {
    items: [{ subitems: []}],
})

Subitems was not defined in your example. This should fix it.

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

2 Comments

No. this is just an example of the scenario. Problem is that i can't access items[0] because it's undefined
Thats because you defined an empty array as items und and empty array is undefined on position 0.
0

try to wrap your v-for into v-if="flag"
define your flag in instance as false
once your data comes from backend change the flag...

Comments

0

Try this:

<div v-if="items.length > 0" v-for="item in items[0].subItems">{{item.name}}</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.