2017-04-06 64 views
1

我試圖從其餘api中獲取一些數據。但是,結果this.someData仍然未定義。從其餘api返回數據

我的成分如下

<template> 
    <div class="list"> 
    <h1>List</h1> 
    <pre>msg: {{msg}}</pre> 
    </div> 
</template> 

<script> 
    import Vue from 'vue' 
    import VueResource from 'vue-resource' 
    Vue.use(VueResource) 

    export default { 
    name: 'list', 
    data() { 
     this.$http.get('http://localhost:8080/api/posts/filter?username=tons').then(response => { 
     // get body data 
     this.someData = response.body 
     console.log(this.someData) 
     }, response => { 
     // error callback 
     }) 

     return { 
     msg: this.someData + 'somedata' 
     } 
    } 
    } 
</script> 

任何人有一個關於我做錯了什麼線索?

+0

如果你在瀏覽器中看到'http:// localhost:8080/api/posts/filter?username = tons',你會看到結果嗎? – dave

回答

1

'data'應該只是屬性。有'方法'您可以獲取某些內容,然後填充您的'數據'屬性。

正確的代碼看起來是這樣的:

<script> 
    export default { 
     data: function() { 
      return { 
       someData: null 
      } 
     }, 
     methods: { 
      getData: function() { 
       // fetch here 
       this.someData = response.body; 
      } 
     }, 
     mounted() { 
      this.getData(); // or trigger by click or smth else 
     } 
    } 
</script> 

在您的模板,你可以再{{ someData }}

@Bert_Evans是正確的,你可以做一些基本的計算中的「數據」,但他們應該syncronous ,因爲反應性在Vue中起作用。

+0

在返回對象之前在數據中做一些計算是完全可以接受的。只是不在這種情況下。 – Bert

+0

當然,但不提取數據。 – wostex

+0

這是Evan You(Vue的創建者)在data()中使用異步方法的一個示例。這完全取決於你如何去做。 https://jsfiddle.net/yyx990803/kyt43L2r/ – Bert