0

我在我的最新项目中使用 Vue.js,在项目的一部分中,我需要渲染一个存储在数据库中的树视图 - 我使用 Vue.js 树视图示例作为基础,并且数据来自我的服务器正确的格式。

我找到了一种修改示例以从 js 加载数据的方法,但是到它这样做的时候,组件已经被渲染了。当我使用来自服务器的数据预加载 var 时,我检查了数据是否有效。

我将如何更改以从 ajax 加载此负载?

我的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;

            }
        });
    }
}
})

模板:

<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>

和html:

<ul id="demo">
  <item
    class="item"
    :model="treeData">
  </item>
</ul>
4

1 回答 1

3

问题出在$.ajax()通话中。self处理程序中的值success有错误的值

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

使用context选项和this.treeData

$.ajax({
    url: 'http://example.com/api/categories/channel/treejson',
    type: 'get',
    context: this,    // tells jQuery to use the current context as the context of the success handler
    dataType: 'json',
    async: false,
    success: function (data) {
        this.treeData = data;
    }
});

或将var self = this线移动到正确的位置之前$.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;
        }
    });
}
于 2016-09-13T14:53:45.960 回答