For my latest project, I am incorporating Vue.js. One part of the project requires rendering a tree view that is stored in a database. I have taken inspiration from the Vue.js tree view example and have successfully retrieved the data from my server in the correct format.
I have managed to tweak the example to load the data from JavaScript. However, there is a delay as the component is already rendered by the time the data loads. I have confirmed that the data functions properly when I preload a variable with the server data.
How can I adjust the setup to allow for loading data via AJAX?
This is my JavaScript:
Vue.component('item', {
template: '#item-template',
props: {
model: Object
},
data: function() {
return {
open: false
}
},
computed: {
isFolder: function() {
return this.model.children && this.model.children.length
}
},
methods: {
toggle: function() {
if (this.isFolder) {
this.open = !this.open
}
},
changeType: function() {
if (!this.isFolder) {
Vue.set(this.model, 'children', [])
this.addChild()
this.open = true
}
}
}
})
var demo = new Vue({
el: '#demo',
data: {
treeData: {}
},
ready: function() {
this.fetchData();
},
methods: {
fetchData: function() {
$.ajax({
url: 'http://example.com/api/categories/channel/treejson',
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
var self = this;
self.treeData = data;
}
});
}
}
})
The template:
<script type="text/x-template" id="item-template">
<li>
<div
:class="{bold: isFolder}"
@click="toggle"
@dblclick="changeType">
@{{model.name}}
<span v-if="isFolder">[@{{open ? '-' : '+'}}]</span>
</div>
<ul v-show="open" v-if="isFolder">
<item
class="item"
v-for="model in model.children"
:model="model">
</item>
</ul>
</li>
</script>
And the HTML:
<ul id="demo">
<item
class="item"
:model="treeData">
</item>
</ul>