2017-04-06 68 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