如何在Vue.js中加载页面后使用$http.get中的数据

How to use data from $http.get after page load in Vue.js?

本文关键字:http 数据 get Vue js 加载      更新时间:2023-09-26

我不知道如何在$http.get请求完成后在Vue.js中执行函数。在下面的示例中,我希望在页面加载后立即自动选择foobar的一个元素,但这仅在存在警报时有效。

new Vue({
    el: '#foo',
    data: {
        foobar: [],
        foobar_selected: []
    },
    ready: function() {
        this.fetchFoobar();
        alert('silly');
        this.selectFoobar(2);
    },
    methods: {
        fetchFoobar: function () {
            this.$http.get('foobar_to_fetch', function (foobar_fetched) {
                this.foobar = foobar_fetched;
            })
        },
        selectFoobar: function (index) {
            this.foobar_selected.push(this.foobar[index]);
        }
    }
});

-

<div id="foo">
    <h2>Foobars</h2>
    <table>
        <tr v-repeat="foobar">
            <td>{{ id }}</td>
            <td>{{ name }}</td>
            <td><button v-on="click: selectFoobar($index)">select</button></td>
        </tr>
    </table>
    <h2>Selected Foobars</h2>
    <table>
        <tr v-repeat="foobar_selected">
            <td>{{ id }}</td>
            <td>{{ name }}</td>
        </tr>
    </table>
</div>

上面写着https://github.com/vuejs/vue-resourceget的第三个参数success,但我不明白在这种情况下应该如何使用它。至少这是有效的:

this.$http.get('foobar_to_fetch', function (foobar_fetched) {
    this.foobar = foobar_fetched;
}, alert('useless'));

但事实并非如此:

this.$http.get('foobar_to_fetch', function (foobar_fetched) {
    this.foobar = foobar_fetched;
}, this.selectFoobar(2));

在Vue.js中,正确的方法是什么?

我使用的是Vue 0.11.10和Vue资源0.1.16。

get具有以下签名:

get(url, [data], [success], [options])

data在方括号中,这意味着参数是可选的。由于data被定义为:

Object | string-要作为请求消息数据发送的数据

您不是在传递对象/字符串作为函数的第二个参数。这意味着您传递的第二个参数被解释为success回调函数这不一定是第三个论点!

如果你这样做:

this.$http.get('foobar_to_fetch', function(data, status, request) {
  this.foobar = data;
  this.selectFoobar(2);
});

理论上应该是可行的。不过,这只是一个猜测,基于我对你在问题中链接的Vue文档的浏览。