MSC
MSC

Reputation: 3386

Vue fails to render data object which has a parent

I need a JS tree object in which child nodes know who their parents are. Vue seems OK with this, at least as far as displaying the correct infinitely expandable object in Vue Devtools goes:

enter image description here

... and displaying the correct parent in the console:

enter image description here

The problem is that Vue errors when trying to render that data on a page:

HTML

<ol>
  <li>
    <b>family.name</b> {{ family.name }}
  </li>
  <li>
    <b>family.children[0].name</b> {{ family.children[0].name }}
  </li>
  <li>
    <b>family.children[1].name</b> {{ family.children[1].name }}
  </li>   
  <li>
  <!-- Add the extra brackets to this to see the "object" error -->
    <b>family.children[0].parent.name</b> { family.children[0].parent.name }
  </li>   
</ol>

JS

    var app = new Vue({
    el: '.container',
    data: {
        family: {
            name: "Dad",
            children: [
                {
                    name: "Marcus",
                    children: [
                        {
                            name: "Bob"
                        }
                    ]
                },
                {
                    name: "Anna",
                    children: [
                        {
                            name: "Ringo"
                        }
                    ]       
                }           
            ]
        }
    },
    mounted() {
        this.family.children[0].parent = this.family;
        this.family.children[0].children[0].parent = this.family.children[0];
        this.family.children[1].parent = this.family;
        this.family.children[1].children[0].parent = this.family.children[1];
    }
  });

There is a live example if you prefer at https://s3-ap-southeast-2.amazonaws.com/mscau/vue-parenting.htm.

Does anyone know how to overcome this obstacle?

Upvotes: 1

Views: 130

Answers (1)

Matt
Matt

Reputation: 44058

You are setting up that relationship in mounted() lifecycle hook which occurs after the first render, so the render will fail before you even set this up.

If you do this work inside created() hook instead, it will set it up before the first render to avoid the failure.

See lifecycle diagram for more detailed info about these hooks.

Upvotes: 2

Related Questions