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.
    – Bert
    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)? 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.

2
  • No. this is just an example of the scenario. Problem is that i can't access items[0] because it's undefined
    – Razinar
    Feb 16, 2018 at 13:51
  • 1
    Thats because you defined an empty array as items und and empty array is undefined on position 0.
    – Thomas
    Feb 16, 2018 at 17:20
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...

0

Try this:

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.