如何在Vue.js中加载页面后使用$http.get中的数据
How to use data from $http.get after page load in Vue.js?
我不知道如何在$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-resource是get
的第三个参数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文档的浏览。
相关文章:
- 如何从HTTP上下文对象中获取Post数据
- 使用2个控制器管理工厂JSON$http数据
- 访问Protractor/E2E测试中的$http数据(AngularJS)
- $http中的Angular 1数据绑定承诺不起作用
- 如何检查提供程序以查看 HTTP 数据是否已准备就绪
- Grails - 在javascript中访问http数据
- 刷新从承诺返回$http数据
- 显示来自 http 数据的多个用户,而不是单个用户
- 从 Angular 服务返回 http 数据
- AngularJS$http数据未正确返回
- Angular JS从控制器中的工厂访问$http数据
- AngularJS 1.5:组件获胜't加载http数据
- 如何使用javascript加载http数据
- 使用$q.all()从AngularJS中的函数获取$http数据
- 我如何让我的angularjs工厂只获取http数据一次
- AngularJS美元范围.Push不从$http数据响应更新视图
- 使用karma jasmine对http数据进行单元测试没有得到正确的结果
- 使AngularJS ui路由器/应用程序等待$http数据以阻止FOUC
- 使用javascript/jquery增量读取http数据流
- AngularJS,我如何使用服务来捕获HTTP数据并将其绑定到我的控制器