2017-03-16 75 views
1

我使用jQuery ajax来请求api并获取响应,但数据无法呈现。有人知道如何解决这个问题吗?Vuejs不呈现来自ajax的数据

var app = new Vue({ 
 
    //router, 
 
    data: { 
 
     people: null 
 
    }, 
 
    created: function() { 
 
     $.ajax({ 
 
     url: 'test.php', \t \t \t 
 
     }).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> 
 

 
     
 

代码中使用VUE路由器: 虽然我使用Vue的路由器,甚至我用箭头功能。模板不能由Vue渲染。我是否滥用Vue路由器?

// 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({ 
 
\t mode: 'hash', 
 
\t base: window.location.href, 
 
\t routes: [ 
 
     {path: '#/', component: PeopleListing}, 
 
     {name: 'person', path: '/:id', component: PersonDetail } 
 
    ] 
 
}); 
 

 

 

 

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

回答

3

范围的,这是创建问题,使用箭头之类的函数如下:

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'); 

你能得到关于这个问题here更多细节。

+0

非常感谢您的帮助。但它不起作用,如果我使用