简体   繁体   English

Vue.js 2:从 AJAX 方法获取数据

[英]Vue.js 2: Get data from AJAX method

I'm new to Vue, and I'm attempting to grab the data via AJAX in a method.我是 Vue 的新手,我正在尝试通过 AJAX 以一种方法获取数据。

I know the method is working.我知道该方法有效。

Here's the Vue code:这是Vue代码:

Vue.component('sub-folder', {
    props: ['folder'],
    template: '<a href="#">{{folder.title}}</a>'
});

var buildFoldersList = new Vue({
    el: '#sub-folders',
    data: {
        foldersList: this.foldersList
    },
    methods: {
        buildFolders: function () {
            $.ajax({
                url: base_url + 'api/folder/get_subfolders/' + browser_folder_id,
                method: 'POST',
                data: {
                    "folder_id": browser_folder_id
                },
                success: function (data) {
                    console.log("Data");
                    console.log(data);
                    this.foldersList = data;
                },
                error: function (error) {
                    alert(JSON.stringify(error));
                }
            });
        }
    }
});

Here's the HTML:这是HTML:

<div class="list-group" id="sub-folders">
    <sub-folder v-for="folder in foldersList" :key="folder.folder_id" v-bind:folder="folder"></sub-folder>
</div>

At the moment, the containing template is running, but since the method isn't getting executed, there's no data.目前,包含模板正在运行,但由于该方法没有被执行,因此没有数据。

I've tried everything I know to trigger the method, but I've run out of ideas.我已经尝试了我所知道的一切来触发该方法,但我已经没有想法了。

It seems you are not calling the buildFolders method at all, you can call it from the created hook of vue.js like following:看来您根本没有调用buildFolders方法,您可以从 vue.js 的created钩子中调用它,如下所示:

var buildFoldersList = new Vue({
    el: '#sub-folders',
    data: {
        foldersList: []
    },
    created () {
       this.buildFolders()
    },
    methods: {
        buildFolders: function () {   
            var self = this 
            $.ajax({
                url: base_url + 'api/folder/get_subfolders/' + browser_folder_id,
                method: 'POST',
                data: {
                    "folder_id": browser_folder_id
                },
                success: function (data) {
                    console.log("Data");
                    console.log(data);
                    self.foldersList = data;
                },
                error: function (error) {
                    alert(JSON.stringify(error));
                }
            });
        }
    }
});

Also you can relook at how you are using this, as scope of this will change in $.ajax method as happened here , see the explanation here .你也可以重新看看你是如何使用它的,因为它的范围this$.ajax方法中发生变化,就像这里发生的那样,请参阅这里的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM