Cannot read property of 'Undefined' in vue.js
Asked Answered
T

3

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.

Tameka answered 16/2, 2018 at 10:17 Comment(2)
It's likely your Vue is created before the data is available, which results in the undefined.Coloratura
Why are you loading your data via jQuery, instead of inside Vue (such as inside a mounted() hook)?Wiener
M
10
var vue = new Vue({
  el: '#vue-wrapper',
  data: {
    items: [{ subitems: []}],
})

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

Magbie answered 16/2, 2018 at 10:22 Comment(2)
No. this is just an example of the scenario. Problem is that i can't access items[0] because it's undefinedTameka
Thats because you defined an empty array as items und and empty array is undefined on position 0.Magbie
P
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...

Parkerparkhurst answered 16/2, 2018 at 11:58 Comment(0)
I
0

Try this:

<div v-if="items.length > 0" v-for="item in items[0].subItems">{{item.name}}</div>
Interphase answered 16/2, 2018 at 15:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.