1

I use jQuery ajax to request api and get the respone, but the data cannot be rendered. Does someone know how to fix this problem?

   var app = new Vue({
     //router,
     data: {
      people: null
     },
     created: function() {
      $.ajax({
        url: 'test.php',   
      }).done(function(res){
        console.log(res);
        this.people = JSON.parse(res);
        //console.log('124234234523');
        //console.log(this.people.name);
      });
     }
    }).$mount('#app');
    <div id="app">
      <ol>
        <li v-for="person in people">
          {{ person.name }}
        </li>
      </ol>
    </div>

      
 

Code use vue router: While I use Vue router, even I use arrow function. The template cannot be render by Vue. Whether do I misuse Vue router?

// Listing people component
var PeopleListing = Vue.extend({
  template: '#people-listing-template',
  data: function() {
      return {
        people: this.$parent.people
    }
  }
});


// Create the router
var router = new VueRouter({
 mode: 'hash',
 base: window.location.href,
 routes: [
      {path: '#/', component: PeopleListing},
      {name: 'person', path: '/:id', component: PersonDetail }
    ]
});




var app = new Vue({
    router,
 data: {
  people: null
 },
 created: function() {
  
  $.ajax({
   url: 'test.php',   
  }).done((res) =>{
   //console.log(res);
   this.people = JSON.parse(res);
   //console.log('124234234523');
   //console.log(this.people.name);
  });
 }
}).$mount('#app');
<div id="app">
 <router-view class="view"></router-view>
</div>
  
  <template id="people-listing-template">
    <ul>
  
      <li v-for="person in people">
        {{ person.name }} 
        <router-link :to="{ name: 'person', params: { id: person.guid }}">View Details</router-link>
      </li>
    </ul>
  </template>
jamesxu-e.g.
  • 650
  • 2
  • 10
  • 22

1 Answers1

3

Scope of this is creating issue, use arrow function like following:

var app = new Vue({
 //router,
 data: {
  people: null
 },
 created: function() {
  $.ajax({
    url: 'test.php',            
  }).done((res) => {
    console.log(res);
    this.people = JSON.parse(res);
    //console.log('124234234523');
    //console.log(this.people.name);
  });
 }
}).$mount('#app');

You can get more details about this issue here.

Community
  • 1
  • 1
Saurabh
  • 71,488
  • 40
  • 181
  • 244