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">{{item}}</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
vm: {}
},
mounted: function () {
this.vm.items = [{
"key": "key1"
}];
}
});
</script>
</body>
</html>
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">{{item}}</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
vm: {
items: []
}
},
mounted: function () {
this.vm.items = [{
"key": "key1"
}];
}
});
</script>
</body>
</html>
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