Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display data in a Vue component with ajax

Tags:

ajax

vue.js

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:

  • 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}}

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

like image 253
retrograde Avatar asked Sep 25 '22 21:09

retrograde


1 Answers

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">
like image 55
retrograde Avatar answered Sep 30 '22 06:09

retrograde