最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read property of 'Undefined' in vue.js - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Feb 16, 2018 at 11:19 MLavoie 9,83641 gold badges41 silver badges59 bronze badges asked Feb 16, 2018 at 10:17 RazinarRazinar 7673 gold badges13 silver badges24 bronze badges 2
  • 1 It's likely your Vue is created before the data is available, which results in the undefined. – Bert 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)? – Daniel Beck Commented Feb 16, 2018 at 15:15
Add a ment  | 

3 Answers 3

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

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

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

Try this:

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

评论列表(0)

  1. 暂无评论