Solution to Vue.js Not Binding Complex View Model Objects

I’m new to Vue.js and didn’t realize that you have to fully define the structure of your view model object or bindings will not work.

For example, with this code, I define data: { vm: {} }, but don’t have the items property and then later set the items property in the mounted function.

<html>

<body>
    <div id="app">
        <h2>Items</h2>
        <div v-for="item in vm.items">&#123;&#123;item&#125;&#125;</div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <script>
        var app = new Vue(&#123;
            el: '#app',
            data: &#123;
                vm: &#123;&#125;
            &#125;,
            mounted: function () &#123;
                this.vm.items = [&#123;
                    "key": "key1"
                &#125;];
            &#125;
        &#125;);
    </script>
</body>

</html>

'Without items rendered'
You can see that the items are not rendered, but they do appear in the Vue data model.

It took me a while to figure this out, but when you define “data”, you have to specify the entire schema of the object. It will not work with dynamic objects - at least not to my current knowledge. LMK if there’s a way.

So, I updated my code, like this:

<html>

<body>
    <div id="app">
        <h2>Items</h2>
        <div v-for="item in vm.items">&#123;&#123;item&#125;&#125;</div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <script>
        var app = new Vue(&#123;
            el: '#app',
            data: &#123;
                vm: &#123;
                    items: []
                &#125;
            &#125;,
            mounted: function () &#123;
                this.vm.items = [&#123;
                    "key": "key1"
                &#125;];
            &#125;
        &#125;);
    </script>
</body>

</html>

'With items rendered'

And, as you can see the “items” property is now bound and rendered.

I burned a at least an hour on this today. I hope I save that time for you with this post.

Jon