簡體   English   中英

更改Vue.js示例以使用Ajax

[英]Changing Vue.js example to use ajax

我在最新項目中使用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>

問題出在$.ajax()調用中。 success處理程序中的self值具有錯誤的值

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();之前的正確位置$.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;
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM