ajax 使用ajax在Vue组件中显示数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34382493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display data in a Vue component with ajax
提问by retrograde
I seem to be misunderstanding how to pass data to a Vue.js component with an ajax call.
我似乎误解了如何使用 ajax 调用将数据传递给 Vue.js 组件。
My understanding of how this should work:
我对这应该如何工作的理解:
- I need to create an empty object called campaigns in the data section of my component.
- Then call method "fetchCampaigns" on page ready to replace the data object.
- fetchCampaign method completes an AJAX call and inside of the success callback use this.$set('campaigns', campaigns) to replace the empty campaign object with the newly returned campaign object
- Use v-for on the template to iterate through the campaign object and access values with @{{campaign.type}}
- 我需要在组件的数据部分创建一个名为活动的空对象。
- 然后在准备好替换数据对象的页面上调用方法“fetchCampaigns”。
- fetchCampaign 方法完成 AJAX 调用,并在成功回调内部使用 this.$set('campaigns', campaign) 将空的活动对象替换为新返回的活动对象
- 在模板上使用 v-for 遍历活动对象并使用 @{{campaign.type}} 访问值
My html (I am use vue router, vue resource and laravel blade) :
我的 html(我使用 vue 路由器、vue 资源和 laravel 刀片):
<router-view></router-view>
<template id="campaignBlock" v-for="campaign in campaigns">
<div class="row">
<div class="block">
<div class="block-title">
<h2>Type: <em>@{{campaign.id}}</em></h2>
</div>
<div class="row"><!-- Grid Content -->
<div class="hidden-sm hidden-xs col-md-4 col-lg-4">
<h2 class="sub-header">@{{campaign.title}}</h2>
</div>
</div>
</div><!-- END Grid Content -->
</template>
Vue component
组件
Vue.component('app-page', {
template: '#campaignBlock',
data: function() {
return{
campaigns: []
}
},
ready: function () {
this.fetchCampaigns();
},
methods: {
fetchCampaigns: function () {
var campaigns = [];
this.$http.get('/retention/getCampaigns')
.success(function (campaigns) {
this.$set('campaigns', campaigns);
})
.error(function (err) {
campaigns.log(err);
});
},
}
})
This is the result of my ajax call from console:
这是我从控制台调用 ajax 的结果:
{"campaigns":[{"id":1,"user_id":2,"target_id":1,"name":"Test Campaign","description":"This is a test Campaign","target":"Onboarding","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00","deleted_at":null}]}
I'm not sure why I can't get my vue component to recognize the new data. Anyone see what I'm missing? TIA
我不确定为什么我的 vue 组件无法识别新数据。有人看到我缺少什么吗?TIA
采纳答案by retrograde
Turns out that v-for="campaign in campaigns" should not go on the template tag, but inside of it.
事实证明, v-for="campaign in campaign" 不应该放在模板标签上,而应该放在模板标签内。
So this:
所以这:
<template id="campaignBlock" v-for="campaign in campaigns">
<div class="row">
Should be changed to this:
应该改成这样:
<template id="campaignBlock">
<div class="row" v-for="campaign in campaigns">

