Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property of 'Undefined' in vue.js

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.

like image 591
Razinar Avatar asked Feb 16 '18 10:02

Razinar


People also ask

How do you fix undefined properties Cannot be read?

The “cannot read property of undefined” error occurs when you attempt to access a property or method of a variable that is undefined . You can fix it by adding an undefined check on the variable before accessing it.

What is type error in VUE JS?

There are four main types of errors you're likely to encounter in your Vue. js app: Syntax errors occur when you use the wrong syntax. Runtime errors are caused by illegal operations during execution.

How do I use Vue components?

Open the file in your code editor. Create the component's template section by adding <template></template> to the top of the file. Create a <script></script> section below your template section. Inside the <script> tags, add a default exported object export default {} , which is your component object.


1 Answers

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

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

like image 188
Thomas Avatar answered Oct 13 '22 23:10

Thomas