aarcarr aarcarr - 2 months ago 97
Javascript Question

Changing Vue.js example to use ajax

Im using Vue.js in my latest project and in part of the project i need to render a tree view which is stored in a db - Im using the Vue.js tree view example as a base and have the data coming from my server in the correct format.

Ive found a way to modify the example to load the data from js but by the time it does, the component has already been rendered. Ive checked that the data works when I preload a var with the data from the server.

How would I change things to make this load from ajax?

My js:

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>

Answer

The problem is in the $.ajax() call. The value of self in the success handler has the wrong value

success: function(data) {
    var self = this;    // this = jqXHR object
    self.treeData = data;
}

Either use the context option and this.treeData

$.ajax({
    url: 'http://example.com/api/categories/channel/treejson',
    type: 'get',
    context: this,
    dataType: 'json',
    async: false,
    success: function (data) {
        this.treeData = data;
    }
});

Or move the var self = this line in the correct place right before $.ajax();

fetchData: function () {
    var self = this;

    $.ajax({
        url: 'http://example.com/api/categories/channel/treejson',
        type: 'get',
        dataType: 'json',
        async: false,
        success: function (data) {
            self.treeData = data;
        }
    });
}
Comments