retrograde
retrograde

Reputation: 2979

Display data in a Vue component with ajax

I seem to be misunderstanding how to pass data to a Vue.js component with an ajax call.

My understanding of how this should work:

My html (I am use vue router, vue resource and laravel blade) :

<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:

{"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

Upvotes: 5

Views: 21262

Answers (1)

retrograde
retrograde

Reputation: 2979

Turns out that v-for="campaign in campaigns" should not go on the template tag, but inside of it.

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">

Upvotes: 4

Related Questions