Cannot read property of 'Undefined' in vue.js

Razinar picture Razinar · Feb 16, 2018 · Viewed 12.5k times · Source

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.

Answer

Thomas picture Thomas · Feb 16, 2018
var vue = new Vue({
  el: '#vue-wrapper',
  data: {
    items: [{ subitems: []}],
})

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