2016-12-02 81 views
1

我有一个Spring Data Rest后端,并在src/main/resources/static html + js资产中工作正常。我的问题是我无法理解如何呈现从界面中的web服务中获取的数据。VueJS + Rest API列表呈现问题

如果我将数据显式设置为数组,它可以正常工作(请参阅https://vuejs.org/v2/guide/list.html)。

预先感谢您!

... 
const ListFormsApi = { 
    template: '<div><ul><li v-for=\'item in items\'>{{item.details.Title}}</li></ul></div>', 
    data: function(){ 
    return { 
     items: '' 
    } 
    }, 
    created: function() { 
    this.get() 
    }, 
    methods: { 
    get: function() { 
     axiosInstance.get('/contactTemplate') 
     .then(function (response) { 
      this.items = response.data._embedded.contactTemplate 
     }).catch(function (error) { 
      console.log(error) 
     } 
    ); 
    } 
    } 
} 
... 

的网页非常简单,从文档的例子简单(假设完整的HTML和head标签都存在,以及...

<body> 

    <div id="app"> 
     <h1><router-link to="/">ContactForm Factory!</router-link></h1> 
     <p> 
     <router-link to="/foo">Go to Foo</router-link> 
     <router-link to="/bar">Go to Bar</router-link> 
     <router-link to="/listForms">List Forms</router-link> 
     <router-link to="/listFormsApi">List Forms API</router-link> 
     </p> 
     <router-view></router-view> 
    </div> 

    <script src="https://unpkg.com/vue/dist/vue.js"></script> 
    <script src="https://unpkg.com/[email protected]/dist/vue-router.js"></script> 
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script> 
    <script src="app.js"></script> 


    </body> 

回答

3

我认为这是发生的,因为这个范围不是你所期望的thenaxiosInstance,你需要进行如下修改才能使它工作。

methods: { 
    get: function() { 
    var self = this 
    axiosInstance.get('/contactTemplate') 
     .then(function (response) { 
     self.items = response.data._embedded.contactTemplate 
     }).catch(function (error) { 
     console.log(error) 
     } 
    ); 
    } 

你可以看看我对类似问题here的回答。

+0

你是对的钱,谢谢你! –

1

当你注册。那么()的回调的功能变化方面。

为了保持上下文可以使用bind方法。

methods: { 
    get: function() { 
    axiosInstance.get('/contactTemplate') 
     .then(function (response) { 
     this.items = response.data._embedded.contactTemplate 
     }.bind(this)) // added .bind 
     .catch(function (error) { 
     console.log(error) 
     }); 
    } 
} 
+0

明天我可以试试,saurabh提出的解决方案按预期工作 –

1

VUE资源正在使用response.body而不是data因此寻找更新如下:

methods: { 
    get: function() { 
    axiosInstance 
     .get('/contactTemplate') 
     .then((response) => { 
     this.$set(this.$data, 'items', response.body._embedded.contactTemplate) 
     }) 
     .catch((error) => { 
     console.log(error) 
     }); 
    } 
} 

我还用箭头语法纠正thisthis.$set范围,以确保您设置的反应数据。

如果这仍然不能产生所需的结果,我会确认数据从端点正确返回。如果例如服务器用不正确的内容类型进行响应,则Vue资源具有可用的方法,例如response.json()

+0

我已经阅读过一篇文章,称vue-resource可能会被放弃,因此我决定在此时不使用vue-resource,完成其余的调用通过axios https://medium.com/the-vue-point/retiring-vue-resource-871a82880af4#.s2rc283t0 –